How can I implement eager load in a many-to-many relationship that exists in a pivot table? I've succeed in retrieving it by lazy loading, but I'm trying to find the eager load way (I'm using L8).
I have 5 tables which related to one another as shown below (simplified):
From the 5 tables above, I've created 4 models:
Class
Period
ClassPeriod
, as a pivot modelTeacher
Class
has belongsToMany()
relationship to Period
, which using()
the ClassPeriod
pivot model. Common stuff. Eager loads related to these 3 models have been easily done. However, I'm confused on how can I eager load Teacher
from Class
.
To retrieve Teacher
from Class
by lazy loading as I mentioned, I've created the following:
- Create
teachers
method withbelongsToMany()
relationship inClassPeriod
- Create
getTeachersAttribute
method which calls theteachers
method above
Then the retrievement can be performed in 2 ways:
Way number 1 is using the
pivot
attribute, something like:$classes = Class::with(['periods'])->get(); foreach($classes as $class) { echo $class->pivot->teachers; }
Way number 2 is by utilizing the
appends
property in the model. So insideClassPeriod
, I added:protected $appends = [ 'teachers' ];
thus
Class::with(['periods'])
will haveteachers
appended to the pivot automatically
So, back to the question, how can I achieve the above in eager loads? Is it possible? Your input is much appriciated.
CodePudding user response:
You can call nested relationships with dot .
in your with() method.
So your query will be:
Class::with('periods')->with('class_period.teachers');
And create the relationship in Class :
public function class_period(){return $this->hasMany(ClassPeriod::class,'class_id');}
And in your ClassPeriod class the relationship:
public function teachers(){return $this->belongsToMany(Teachers::class)->using(ClassPeriodTeacher::class);}
You can add wheres and whereRelation to add more logic to your query.