Laravel关联关系中去除重复实体的解决方案
解决Laravel多对多关联返回重复实体的问题
你的问题根源在于licenses中间表中存在同一人员-雇主对的多条记录,而belongsToMany关联默认会把每条中间表记录对应的模型都返回,因此出现了重复的实体。可以通过以下两种方式修正:
方法一:在关联定义中默认添加去重约束
直接修改模型里的关联方法,加入distinct(),让关联查询默认返回唯一实体:
Employer模型修改:
class Employer extends \Illuminate\Database\Eloquent\Model { public function people() { return $this->belongsToMany(Person::class, 'licenses')->distinct(); } // &c }
Person模型修改:
class Person extends \Illuminate\Database\Eloquent\Model { public function employer() { return $this->belongsToMany(Employer::class, 'licenses')->distinct(); } // &c }
distinct()会让底层SQL自动添加DISTINCT关键字,过滤掉重复的模型记录。
方法二:在特定查询场景下动态去重
如果不需要全局默认去重,仅在部分查询中需要唯一实体,可以在调用关联时链式调用distinct():
// 查询某雇主的唯一关联人员 $uniquePeople = $employer->people()->distinct()->get(); // 查询某人员的唯一关联雇主 $uniqueEmployer = $person->employer()->distinct()->get();
如果中间表包含额外字段,担心DISTINCT因这些字段导致去重失效,可以指定具体去重字段(比如模型主键):
$this->belongsToMany(Person::class, 'licenses')->distinct('people.id');
内容的提问来源于stack exchange,提问作者Jay Bienvenu
相关产品推荐
相关产品推荐

