【问题标题】:Distinct pivot results with Eloquent使用 Eloquent 获得不同的枢轴结果
【发布时间】:2014-10-09 04:21:37
【问题描述】:

在我的 Laravel 项目中,我正在打印所有联系人的名片。

在我的联系模型中:

    public function organizations()
    {
       return $this->belongsToMany('Organization')->withPivot('ContractStatus')->withTimestamps();
    }

这样,我可以显示联系人仍在工作的所有公司。

在我的联系人概览页面的页脚中,我想打印出该特定搜索查询的所有关联公司徽标。

但是像这样:

@foreach($contacts as $key => $value)
    @foreach($value->organizations as $organization)

    @endforeach
@endforeach

只要搜索结果包含 2 个为同一公司工作的联系人,就会打印重复的公司徽标。

【问题讨论】:

    标签: laravel many-to-many eloquent


    【解决方案1】:

    在控制器操作中生成一个带有组织的新集合:

    $uniqueOrganizations = new Collection();
    foreach($contacts as $contact)
        $uniqueOrganizations->merge($contact->organizations);
    

    然后将其传递给视图,以显示所有不同的组织

    @foreach($uniqueOrganizations as $org)
          //show org logo
    @endforeach
    

    【讨论】:

      【解决方案2】:

      如果您想列出联系人集合的不同集合,则不要使用关系,而是使用whereHas

      $contactsIds = $contacts->modelKeys();
      
      $organizations = Organization::whereHas('contacts', function ($q) use ($contactsIds) {
        $q->whereIn('contacts.id', $contactsIds);
      })->get();
      

      另一种方法是这个技巧,以防您实际上需要加载关系:

      $organizations = null;
      
      $contacts = Contact::with(['organizations' => function ($q) use (&$organizations) {
        $organizations = $q->get();
      }])->get();
      
      $organizations = $organizations->unique();
      

      这将像往常一样加载关系并运行附加查询并将其结果分配给$organizations

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        相关资源
        最近更新 更多