如何使用相同的eloquent查询两次,但有一个不同的where子句?

时间:2017-01-24 22:24:47

标签: php mysql laravel eloquent reusability

我有这个问题:

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子句。是否可以在不复制整个代码的情况下重用此查询?如果是这样,怎么样?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);
相关问题