Many-to-Many Tripartite Relations in Laravel

I have three models that should be linked in a pivot table: User, Student, Plan. Therefore, each user can subscribe to the plan.

What I have found so far is to create a support element for two models, for example User and Plan, and add student_id as an additional field:

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

One of the problems is that if I try to get plans for a specific user, I will not get a student model, just an identifier, therefore:

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

So, I need to make a second request to get a student model.

Is there any other way to do this, given that I want to make queries in all directions, for example:

 $user->plans() (attaching the students) $student->plans() (attaching the user) $plan->users() (attaching the students) $plan->students() (attaching the users) 
+7
eloquent laravel laravel-5
source share
1 answer

I often use a different model to abstract the relationship between many and many.

We have our relation, which I will call relation .

db structure:

 table relations: id, user_id, student_id, plan_id 

The application has the following four models:

  • User
  • Student
  • Plan
  • Communication

Here's how we connect the four models using relationships:

User, plan, student:

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

Relationship:

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

You can get objects 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; } 

This is the only solution I have found in all the time that I have been developing on Laravel.

+9
source share

All Articles