如何在Laravel中为ORM eager加载添加多个键约束?

时间:2017-11-16 18:20:30

标签: laravel orm eager-loading

假设我有三个关系:

 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_seatsdepartment分组quota访问number_of_seats,我想再次按quotadepartment分组quotas }。我需要使用laravel ORM eager loading来完成这项任务。

我可以使用以下内容departments访问所有\App\Quota::with('departments')->get();

\App\Department::with('quotas')->get();

和使用相反的东西:

number_of_seats

是的,这是多对多的关系。 但是,如何按上述方式访问JSON

我需要这个,因为我要将关系作为REST的{​​{1}}序列化数据提供。

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;
       }
    }