【问题标题】:Three-way many-to-many relationship in LaravelLaravel 中的三向多对多关系
【发布时间】:2015-08-19 10:00:39
【问题描述】:

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

到目前为止,我发现为两个模型创建一个数据透视表,比如用户和计划,并将 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)

【问题讨论】:

    标签: laravel eloquent laravel-5


    【解决方案1】:

    我经常使用另一种模型来抽象三向多对多关系。

    我们有我们的关系,我将其称为关系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 上开发的唯一解决方案。

    【讨论】:

    • 卡洛斯的好答案。
    • 不能以这种方式使用 attach() 和 detach() 方法。
    • 在Relation模型上,为什么是belongsToMany?不应该是属于吗?这样每个关系都有一个学生、一个用户和一个计划,对吗?
    猜你喜欢
    • 2013-05-27
    • 2018-03-28
    • 2013-06-22
    • 2017-11-06
    • 2021-05-16
    • 2016-08-18
    • 1970-01-01
    • 2017-05-22
    相关资源
    最近更新 更多