Laravel中的三方多对多关系

bab*_*eii 8 laravel eloquent laravel-5

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

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

$user->plans()->attach([1 => ['student_id' => $student_id]);
Run Code Online (Sandbox Code Playgroud)

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

return $this->BelongsToMany('App\Plan', 'plans_students_users', 'user_id', 'plan_id')
->withPivot('student_id');
Run Code Online (Sandbox Code Playgroud)

所以,我必须做第二个查询来获得学生模型.

有没有其他方法可以解决它,因为我想要在所有方向进行查询,例如:

$user->plans() (attaching the students)
$student->plans() (attaching the user)
$plan->users() (attaching the students)
$plan->students() (attaching the users)
Run Code Online (Sandbox Code Playgroud)

Car*_*ata 10

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

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

db结构:

table relations: id, user_id, student_id, plan_id
Run Code Online (Sandbox Code Playgroud)

该应用程序有以下四种型号:

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

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

用户,计划,学生:

function relations() {
   return $this->hasMany(Relation::class);
}
Run Code Online (Sandbox Code Playgroud)

关系:

function student() {
   return $this->belongsToMany(Student::class);
}

function user() {
   return $this->belongsToMany(User::class);
}

function plan() {
   return $this->belongsToMany(Plan::class);
}
Run Code Online (Sandbox Code Playgroud)

您可以检索这样的实体:

//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;
}
Run Code Online (Sandbox Code Playgroud)

它是我在Laravel上开发的唯一解决方案.

  • 在关系模型上,为什么它属于ToMany?不应该属于那个?这样每个关系都有一个学生,一个用户和一个计划,对吗? (5认同)