Laravel - Relations with multiple ids
Ad
I have two table:
1. Rooms
2. Facilities
The Facilities rooms contains the id and a varchar column.
The Room table contains a columns (facilities_id) with, obviously, the id from the facilities table. In that column I have a multiple value, separated by a comma (1,3,4).
What is the best way to make a relation between them? Like "belongsTo" relations but with multi ids.
Ad
Answer
Ad
Like Alexander M. said, would be better if you change your structure. e. g.:
Schema::create('facilities', function (Blueprint $table) {
$table->increments('id');
$table->string('column')->unique();
$table->timestamps();
});
Schema::create('facility_room', function (Blueprint $table) {
$table->integer('facility_id')->unsigned();
$table->integer('room_id')->unsigned();
$table->foreign('facility_id')->references('id')->on('facilities')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('room_id')->references('id')->on('rooms')
->onUpdate('cascade')->onDelete('cascade');
});
Schema::create('rooms', function (Blueprint $table) {
$table->increments('id');
$table->string('column')->unique();
$table->timestamps();
});
In your Facility Model:
public function rooms()
{
return $this->belongsToMany(Room::class);
}
In your Room Model:
public function facilities()
{
return $this->belongsToMany(Facility::class);
}
In our application:
$room = Room::find($id);
$facilities = $room->facilities();
Ad
source: stackoverflow.com
Related Questions
Ad
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad