【问题标题】:How to add multiple key constraints for ORM eager loading in Laravel?如何在 Laravel 中为 ORM 急切加载添加多个键约束?
【发布时间】:2017-11-16 18:20:29
【问题描述】:

假设我有三个关系:

 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 分组的department 访问number_of_seats。我需要使用 laravel ORM 急切加载来完成这项任务。

我可以使用departments访问所有quotas

\App\Quota::with('departments')->get();

还有相反的使用 by:

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

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

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

【问题讨论】:

    标签: laravel orm eager-loading


    【解决方案1】:

    如果两个模型都是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;
           }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2013-12-25
      • 2016-12-28
      • 2015-11-17
      相关资源
      最近更新 更多