Laravel - Relations with multiple ids

- 1 answer

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
Ad