Nested 'AND OR' Query in Eloquent

别说谁变了你拦得住时间么 提交于 2019-12-20 11:14:08

问题


I'm currently attempting to create a nested query, as follows:

public function getChallenge($user_id, $opponent_id)
{
    $challenge = $this->challenges()
            ->where('open', true)
            ->where(function($query) use ($user_id, $opponent_id) {
                    $query->where('player_1', $user_id)
                          ->where('player_2', $opponent_id);
                })
                 ->orWhere(function($query) use ($opponent_id, $user_id) {
                    $query->where('player_1', $opponent_id)
                          ->where('player_2', $user_id);
                })
            ->first();

    return $challenge;
}

This creates the following query for example:

select * from `site_challenges_leagues` 
where `site_challenges_leagues`.`league_id` = '1' 
and `open` = '1'
and (`player_1` = '3' and `player_2` = '1') 
or (`player_1` = '1' and `player_2` = '3') 
limit 1

However, this always returns the first value in the table (where open is either 1 or 0), which is incorrect. For the query to be correct, it needs to contain both sets of AND queries in brackets, as follows:

 select * from `site_challenges_leagues` 
 where `site_challenges_leagues`.`league_id` = '1' 
 and `open` = TRUE 

 and ((`player_1` = '3' and `player_2` = '1') 
 or (`player_1` = '1' and `player_2` = '3'))

 limit 1

Is it possible to do this in Laravel? I attempted to do this; however, it failed:

public function getChallenge($user_id, $opponent_id)
{
    $challenge = $this->challenges()
            ->where('open', true)
            ->where(function($q) use ($user_id, $opponent_id) {
                $q->where(function($query) {
                        $query->where('player_1', $user_id)
                              ->where('player_2', $opponent_id);
                    })
                  ->orWhere(function($query) {
                        $query->where('player_1', $opponent_id)
                              ->where('player_2', $user_id);
                    })
                })
            ->first();

    return $challenge;
}

Any help is greatly appreciated.


回答1:


You were very close to the answer

$challenge = $this->challenges()
        ->where('open', true)
        ->where(function($q) use ($user_id, $opponent_id) {
            $q->where(function($query) use ($opponent_id, $user_id){
                    $query->where('player_1', $user_id)
                          ->where('player_2', $opponent_id);
                })
              ->orWhere(function($query) use ($opponent_id, $user_id) {
                    $query->where('player_1', $opponent_id)
                          ->where('player_2', $user_id);
                });
            })
        ->first();

Here are the differences between two codes



来源:https://stackoverflow.com/questions/25129117/nested-and-or-query-in-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!