Laravel 多对多关系搜索
Posted
技术标签:
【中文标题】Laravel 多对多关系搜索【英文标题】:Laravel many to many relation search 【发布时间】:2015-10-29 01:13:41 【问题描述】:我现在有三个模型
用户
public function languages()
return $this->belongsToMany('App\Language');
报纸
public function languages()
return $this->belongsToMany('App\Language');
语言
public function users()
return $this->belongsToMany('App\User');
public function newspapers()
return $this->belongsToMany('App\Newspaper');
我已经有了language_user
、language_newspaper
表
在修补程序中,我已经通过 attach() blablabla 成功检索了这两个关系。
问题是
我怎么能搜索Newspaper
User
id1 有这个Language
雄辩?这对我来说似乎很复杂。
User id1 -> has language en, zh
Newspaper id1 -> has language en, jp
->好的
Newspaper id2 -> has language zh
->不行
我试过了,但不确定它是否正确
$where = [];
foreach ($agent->languages as $language)
array_push($where, $language->id);
$newspapers = Newspaper::
join('language_newspaper', function ($join) use ($where)
$join->on('newspaper.id', '=',
'langauge_newspaper.newspaper_id')
->whereIn('langauge_newspaper.newspaper_id', $where);
)
->groupBy('newspaper.id')
->get();
【问题讨论】:
【参考方案1】:您应该可以在这种情况下使用whereHas
,如下所示:
$newspapers = Newspaper::whereHas('languages', function ($q) use ($agent)
$q->whereIn('id', $agent->languages->lists('id)->all());
)->get();
【讨论】:
以上是关于Laravel 多对多关系搜索的主要内容,如果未能解决你的问题,请参考以下文章