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
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:
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.