Suppose I have three relations:
1. departments
- id (primary)
- name
2. quotas
- id (primary)
- name
3. department_quota
- id (primary)
- department_id (foreign)
- quota_id (foreign)
- number_of_seats
- unique(department_id, quota_id)
Now, I want to access number_of_seats
per department
grouped by quota
, again I want to access number_of_seats
per quota
grouped by department
. I need to do this task using laravel ORM eager loading.
I can access all quotas
with departments
using :
\App\Quota::with('departments')->get();
and also the opposite thing using by:
\App\Department::with('quotas')->get();
Yes, this is a many-to-many relation.
But how can I access the number_of_seats
as stated above ?
I need this because I am to serve the relation as JSON
serialized data for REST
.
If both models are belongsToMany
you can add withPivot()
to your departments()
method.
public function departments(){
return $this->belongsToMany('App\Department')->withPivot('number_of_seats');
}
it will be included in the json collection and it can be reached via code with
foreach(Quota::with('departments')->get() as $quota){
foreach($quota->departments as $department){
echo $department->pivot->number_of_seats;
}
}