中的三向多对多关系

中的三向多对多关系

本文介绍了Laravel 中的三向多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个需要在数据透视表中关联的模型:用户、学生、计划.因此,每个用户都可以为学生订阅一个计划.

I have three models that need to be related in a pivot table: User, Student, Plan. So each user can subscribe a student to a plan.

到目前为止我发现的是为两个模型创建一个数据透视表,比如 User 和 Plan,并将 student_id 作为一个额外的字段附加:

What I've found so far is to create a pivot for two of the models, say User and Plan, and attach the student_id as an extra field:

$user->plans()->attach([1 => ['student_id' => $student_id]);

这样做的一个问题是,如果我尝试检索特定用户的计划,我不会得到学生模型,只有 id,所以:

One problem with this is that if I try to retrieve the plans for a particular user, I don't get the student model, just the id, so:

return $this->BelongsToMany('AppPlan', 'plans_students_users', 'user_id', 'plan_id')
->withPivot('student_id');

因此,我必须进行第二次查询才能获得学生模型.

So, I'd have to do a second query to get the student model.

考虑到我想向各个方向进行查询,是否还有其他方法可以解决,例如:

Is there any other way to go about it, given that I'll want to make queries in all directions, e.g:

$user->plans() (attaching the students)
$student->plans() (attaching the user)
$plan->users() (attaching the students)
$plan->students() (attaching the users)

推荐答案

我经常使用另一个模型来抽象一个三路多对多关系.

I often use another model to abstract a three-way many to many relations.

我们有我们的关系,我称之为关系relation.

We have our relation I will call the relation relation.

db 结构:

table relations: id, user_id, student_id, plan_id

该应用有以下四种模式:

The app has the following four models:

  • 用户
  • 学生
  • 计划
  • 关系

以下是我们如何使用关系连接四个模型:

Here is how we connect the four models using Relationships:

用户、计划、学生:

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);
}

您可以像这样检索实体:

You can retrieve the entities like this:

//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 上开发的唯一解决方案.

Its the only solution I have found in all the time I have been developing on Laravel.

这篇关于Laravel 中的三向多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 23:21