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

How to add multiple key constraints for ORM eager loading in Laravel?

假设我有三个关系:

 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)

现在,我想访问按 quota 分组的每个 department number_of_seats,我想再次访问按 quota 分组的 number_of_seats 15=]。我需要使用 laravel ORM 预加载来完成此任务。

我可以通过 departments 使用 :

访问所有 quotas
\App\Quota::with('departments')->get();

还有相反的使用 by:

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

是的,这是一个多对多的关系。 但是我怎样才能访问如上所述的 number_of_seats 呢?

我需要这个,因为我要将关系作为 JSON 序列化数据提供给 REST

如果两个模型都是 belongsToMany,您可以将 withPivot() 添加到您的 departments() 方法中。

public function departments(){
    return $this->belongsToMany('App\Department')->withPivot('number_of_seats');
}

它将包含在 json collection 中,并且可以通过

代码访问
foreach(Quota::with('departments')->get() as $quota){
       foreach($quota->departments as $department){
           echo $department->pivot->number_of_seats;
       }
    }