【发布时间】:2018-04-25 07:47:43
【问题描述】:
我正在使用 Laravel 5 并且正在尝试了解我的关系。
我有 2 张桌子、学生和房间。每个房间可以有很多学生,每个学生可以有很多房间。
这会是双向的多对多关系吗?我需要一个数据透视表来实现这一点吗?
【问题讨论】:
标签: laravel
我正在使用 Laravel 5 并且正在尝试了解我的关系。
我有 2 张桌子、学生和房间。每个房间可以有很多学生,每个学生可以有很多房间。
这会是双向的多对多关系吗?我需要一个数据透视表来实现这一点吗?
【问题讨论】:
标签: laravel
是的,您描述的是多对多关系,为此您需要一个数据透视表。
您的三个表格如下所示: (这可能与您的实际表格不同)
students
id (primary key)
name
age
rooms
id (primary key)
room_size
bedroom_count
注意:默认情况下,数据透视表的名称由两个模型名称(单数形式)组成,按字母顺序排列。所以在这种情况下:学生 + 房间 = room_student。
room_student(数据透视表)
room_id (foreign key to 'rooms')
student_id (foreign key to 'students')
数据透视表迁移:
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 和 Student 型号:
class Room extends Model {
// ...
public function students()
{
$this->belongsToMany(App\Student::class);
}
}
class Student extends Model {
// ...
public function rooms()
{
$this->belongsToMany(App\Room::class);
}
}
【讨论】:
【讨论】:
是的,您可以实现多对多关系,并且您肯定需要数据透视表来实现多对多关系。 在这种情况下,您可以创建像 room_student 这样的数据透视表,并在其中添加 room_id 和 student_id 列。然后只需在模型中使用 belongsToMany 方法定义关系,并记住在要附加功能的任何地方使用 attach 方法。
【讨论】:
【讨论】: