2017-01-24 44 views
0

我有這個疑問:如何使用同一個雄辯查詢兩次,但使用一個不同的where子句?

User::leftJoin('friends', function ($join) { 
    $join->on('friends.user_id_1', '=', 'users.id') 
     ->orOn('friends.user_id_2', '=', 'users.id'); 
}) 
->where(function ($query) use ($myID) { 
    // Group orwhere functions so the query builder knows these belong together 
    $query->where([ 
     'friends.user_id_1' => $myID, 
     'friends.accepted' => true 
    ]) 
    ->orWhere([ 
     'friends.user_id_2' => $myID, 
     'friends.accepted' => true 
    ]); 
}) 
->where('users.id', '!=', $myID) // Exclude the user with id $myID 
->get(); 

https://stackoverflow.com/a/41832867/5437864

我想兩次使用此查詢,但使用不同的where子句。是否可以在不復制整個代碼的情況下重用此查詢?如果是這樣,怎麼樣?

+0

是的,是的。 – nogad

+0

@nogad謝謝,但如何? :) – Z0q

+0

請在您的文章中至少包含部分鏈接內容,否則鏈接可能無法與時間匹配,問題將無法理解 – Icarus

回答

0
$query = User::leftJoin('friends', function ($join) { 
    $join->on('friends.user_id_1', '=', 'users.id') 
     ->orOn('friends.user_id_2', '=', 'users.id'); 
}) 
->where(function ($query) use ($myID) { 
    // Group orwhere functions so the query builder knows these belong together 
    $query->where([ 
     'friends.user_id_1' => $myID, 
     'friends.accepted' => true 
    ]) 
    ->orWhere([ 
     'friends.user_id_2' => $myID, 
     'friends.accepted' => true 
    ]); 
}); 

增加額外哪裏現有的查詢

$query->where('users.id', '!=', $myID) 


$query->get(); 

檢查此鏈接爲另一個例子

Example

+0

這不起作用。另一個鏈接是使用查詢生成器。 – Z0q

+0

它不會給出任何錯誤,但它將2個過濾器應用於相同的查詢,而不是每個副本一個過濾器。我使用了'clone'關鍵字(請參閱我的答案)。 – Z0q

+0

我其實並不瞭解你,你是什麼意思。但是,你做了同樣的事情,有更長的路要走。沒有任何2個過濾器。你可以每次添加一些條件給我提供的主'$ query'。 – Rashad

0

我使用的PHP克隆keyword。我不確定這是否是最好的解決方案,但它有幫助。歡迎任何其他建議。

$friends_query = User::leftJoin('friends', function ($join) { 
    $join->on('friends.user_id_1', '=', 'users.id') 
     ->orOn('friends.user_id_2', '=', 'users.id'); 
}) 
->where(function ($query) use ($myID) { 
    // Group orwhere functions so the query builder knows these belong together 
    $query->where([ 
     'friends.user_id_1' => $myID, 
     'friends.accepted' => true 
    ]) 
    ->orWhere([ 
     'friends.user_id_2' => $myID, 
     'friends.accepted' => true 
    ]); 
}); 

$friends_me = clone $friends_query; 
$friends_me = $friends_me->where('users.id', '!=', $myID); 

$friends_others = clone $friends_query; 
$friends_others = $friends_others->where('users.id', '=', $myID); 
相關問題