假设我有三个关系:
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)
现在,我希望按number_of_seats
按department
分组quota
访问number_of_seats
,我想再次按quota
按department
分组quotas
}。我需要使用laravel ORM eager loading来完成这项任务。
我可以使用以下内容departments
访问所有\App\Quota::with('departments')->get();
\App\Department::with('quotas')->get();
和使用相反的东西:
number_of_seats
是的,这是多对多的关系。
但是,如何按上述方式访问JSON
?
我需要这个,因为我要将关系作为REST
的{{1}}序列化数据提供。
答案 0 :(得分:0)
如果两个模型都是belongsToMany
,您可以将withPivot()
添加到departments()
方法中。
public function departments(){
return $this->belongsToMany('App\Department')->withPivot('number_of_seats');
}
它将包含在json集合中,可以通过
代码访问它foreach(Quota::with('departments')->get() as $quota){
foreach($quota->departments as $department){
echo $department->pivot->number_of_seats;
}
}