Three-way many-to-many relationship in Laravel

后端 未结 1 1034
野性不改
野性不改 2020-12-14 12:20

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.

What I\'ve found so far is to crea

相关标签:
1条回答
  • 2020-12-14 12:37

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

    We have our relation I will call the relation relation.

    The db structure:

    table relations: id, user_id, student_id, plan_id
    

    The app has the following four models:

    • User
    • Student
    • Plan
    • Relation

    Here is how we connect the four models using Relationships:

    User, Plan, Student:

    function relations() {
       return $this->hasMany(Relation::class);
    }
    

    Relation:

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

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

    0 讨论(0)
提交回复
热议问题