Laravel 多个 whereHas 关系标准
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26194771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel multiple whereHas criteria for relationship
提问by user3415951
I have two tables - contacts and visits:
我有两个表 - 联系人和访问:
Contacts Table
联系人表
id | name
----- | -------
1 | Joe
2 | Sally
Visits Table
访问表
id | contact_id | pathname | referrer
----- | ------- | ------- | -------
1 | 1 | about | google
2 | 1 | pricing | null
3 | 1 | signup | null
4 | 2 | about | null
5 | 2 | signup | null
Using eloquent, I would like to retrieve all contactsthat have a both a pathname= 'signup' AND a referrer= 'google'.
使用 eloquent,我想检索具有路径名= 'signup' 和引用者= 'google' 的所有联系人。
What I've got so far is:
到目前为止我所得到的是:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->orWhereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
Which properly retrieves all contacts that have visited either the pricing OR signup page.
这会正确检索访问过定价或注册页面的所有联系人。
However, this example would also retrieve Sally(from the example table above), since she visited signup, but was not referred by google. I need a way to only retrieve Joe, who was both referred by google and visited pricing.
但是,此示例还将检索Sally(从上面的示例表中),因为她访问了注册,但未被 google 引用。我需要一种方法来只检索Joe,他被谷歌推荐并访问了定价。
Any ideas? Thanks in advance!
有任何想法吗?提前致谢!
回答by Marcin Nabia?ek
You can use:
您可以使用:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->whereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
回答by Darren Murphy
A refined version of the code above:
上面代码的改进版本:
Contact::whereHas('visits', function($query) {
$query->where('pathname','signup')->where('referrer','google');
})->get();
Several noteworthy points:
几个值得注意的点:
- You can chain
where()
clauses within a closure. - The default operator for a where clause is
=
, so you can omit it. - Use multiple
whereHas()
clauses, when accessing multiple related models.
- 您可以
where()
在闭包中链接子句。 - where 子句的默认运算符是
=
,因此您可以省略它。 whereHas()
访问多个相关模型时,使用多个子句。