BelongsToMany 关系。如何获得唯一行

BelongsToMany relation. How to get unique rows

我在数据库中有下一个 'member_companies' table:

并且在模型 Member 中有一个关系:

public function companies()
{
    return $this->belongsToMany(Company::class, 'member_companies');
}

它 return 我所有有重复的公司。例如,Member::find(238)->companies->pluck('id') return

[
  6,
  5,
  7,
  2,
  10,
  8,
  4,
  13,
  14,
  10,
  8,
  13
]

但我只想要独特的物品。喜欢

[
    6,
    5,
    7,
    2,
    10,
    8,
    4,
    13,
    14,
]   

如何处理 eloquent 关系?

您应该在控制器中使用 unique() 方法:

Member::find(238)->companies->pluck('id')->unique('id');

文档:

The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys

When dealing with nested arrays or objects, you may specify the key used to determine uniqueness

或者在你的关系中你可以使用 groupBy():

public function companies()
{
    return $this->belongsToMany(Company::class, 'member_companies')->groupBy('id');
}

你可以像这样使用group by

Member::with(['companies' => function($query){
    $query->groupBy('id');
}])->get();

我找到了下一个解决方案:

public function companies()
{
    $relation = $this->belongsToMany(Company::class, 'member_companies');

    $relation->getQuery()->getQuery()
        ->joins[0]->table = \DB::raw('(SELECT DISTINCT member_id, company_id FROM member_companies) as member_companies');

    return $relation;
}

但也许这段代码有更精致的变体?

不确定它是否是新添加的,但你可以这样做(至少在 Laravel 7):

public function companies()
{
    return $this->belongsToMany(Company::class, 'member_companies')->distinct();
}