2017-01-24 37 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); 
相关问题