我有三个模型需要在数据透视表中关联:用户、学生、计划。因此,每个用户都可以为学生订阅一个计划。
到目前为止,我发现为两个模型创建一个数据透视表,比如用户和计划,并将 student_id 作为一个额外的字段附加:
$user->plans()->attach([1 => ['student_id' => $student_id]);
这样做的一个问题是,如果我尝试检索特定用户的计划,我不会得到学生模型,只有 id,所以:
return $this->BelongsToMany('App\Plan', 'plans_students_users', 'user_id', 'plan_id')
->withPivot('student_id');
因此,我必须进行第二次查询才能获得学生模型。
考虑到我想在各个方向进行查询,是否还有其他方法可以解决,例如:
$user->plans() (attaching the students)
$student->plans() (attaching the user)
$plan->users() (attaching the students)
$plan->students() (attaching the users)
最佳答案
我经常使用另一种模型来抽象三向多对多关系。
我们有我们的关系,我将其称为关系 relation
.db
结构体:
table relations: id, user_id, student_id, plan_id
该应用程序有以下四种模型:
以下是我们如何使用关系连接四个模型:
用户、计划、学生:
function relations() {
return $this->hasMany(Relation::class);
}
联系人:
function student() {
return $this->belongsToMany(Student::class);
}
function user() {
return $this->belongsToMany(User::class);
}
function plan() {
return $this->belongsToMany(Plan::class);
}
您可以像这样检索实体:
//get the plan of a student related to the user
$user->relations()->where('student_id', $student)->first()->plan();
//get all entities from the relation
foreach ($user->relations as $relation) {
$plan = $relation->plan;
$student = $relation->student;
}
这是我一直在 Laravel 上开发的唯一解决方案。
关于laravel - Laravel 中的三向多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30649810/