Ja, was Sie beschreiben, ist eine many-to-many-Beziehung, und dass Sie eine Pivot-Tabelle benötigen.
Ihre drei Tabellen würde wie folgt aussehen:(dies von Ihren tatsächlichen Tabellen anders aussehen könnte)
students
id (primary key)
name
age
rooms
id (primary key)
room_size
bedroom_count
Hinweis: durch Standard, der Name von Die Pivot-Tabelle besteht aus beiden Modellnamen (in Singularform) in alphabetischer Reihenfolge. Also in diesem Fall: Student + Room = room_student.
room_student
(Drehtisch)
room_id (foreign key to 'rooms')
student_id (foreign key to 'students')
Pivot Tabelle Migration:
class CreateRoomStudentTable extends Migration
{
public function up()
{
Schema::create('room_student', function (Blueprint $table) {
$table->unsignedInteger('room_id');
$table->unsignedInteger('student_id');
// Primary key
$table->primary(['room_id', 'student_id']);
// Both foreign keys
$table->foreign('room_id')
->references('id')
->on('rooms')
->onDelete('cascade');
$table->foreign('student_id')
->references('id')
->on('students')
->onDelete('cascade');
});
}
// ...
Room
und Student
Modelle:
class Room extends Model {
// ...
public function students()
{
$this->belongsToMany(App\Student::class);
}
}
class Student extends Model {
// ...
public function rooms()
{
$this->belongsToMany(App\Room::class);
}
}