[英]Laravel Eloquent: whereHas on relationship involving multiple tables
[英]Laravel multiple whereHas criteria for relationship
我有兩張桌子 - 聯系和訪問:
聯系表
id | name
----- | -------
1 | Joe
2 | Sally
訪問表
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
使用eloquent,我想檢索所有具有路徑名 ='注冊'和引用者 ='谷歌'的聯系人 。
到目前為止我得到的是:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->orWhereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
正確檢索已訪問定價或注冊頁面的所有聯系人。
但是,這個例子也會檢索Sally (來自上面的示例表),因為她訪問了注冊,但沒有被谷歌引用。 我需要一種方法來只檢索Joe ,他既是谷歌和訪問定價。
有任何想法嗎? 提前致謝!
您可以使用:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->whereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
以上代碼的精煉版本:
Contact::whereHas('visits', function($query) {
$query->where('pathname','signup')->where('referrer','google');
})->get();
幾個值得注意的要點:
where()
子句。 =
,因此您可以省略它。 whereHas()
子句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.