使用OR的Laravel雄辩查询构建

时间:2017-09-05 08:28:47

标签: php eloquent laravel-5.4 laravel-eloquent

eloquent查询过滤器:

return $this->games()
        ->where(function ($query) {
            $query->where('active_player_id', '=', $this->id)
                ->where('stage_name', '<>', 'setup');
        })
        ->orWhere(function ($query) {
            $query->where('active_player_id', '<>', $this->id)
                ->where('stage_name', '=', 'setup');
        });

像这样构建SQL:

where `games_players`.`player_id` = '1' 
and (`active_player_id` = '1' and `stage_name` <> 'setup') 
or (`active_player_id` <> '1' and `stage_name` = 'setup')

如何更改eloquent代码以构建此查询(OR周围的括号):

where `games_players`.`player_id` = '1' 
and (
     (`active_player_id` = '1' and `stage_name` <> 'setup') 
  or (`active_player_id` <> '1' and `stage_name` = 'setup')
    ) 

3 个答案:

答案 0 :(得分:2)

您可以通过以下方式实现这一目标:

    ->where('active_player_id',1)
    ->where(function($q){
          $q->where([ ['active_player_id', 1],['stage_name','!=', 'setup'] ])
            ->orWhere([ ['active_player_id','!=', 1],['stage_name', 'setup'] ]
    })->get()

答案 1 :(得分:0)

我现在没有一个Eloquent的实例可以用来测试,但现在它会是这样吗?

awk 'NR==FNR{ if(NR>1) a[$1]=$2; b[$1]=$1; next }
     FNR>1 && $1~ /b[$1] in a && NF<3{ f=$2; $2=a[$1]; $3=f }1' eaf.txt final.txt | column -t

也就是说,你把要组合在一起的条件放在一个匿名函数上?

答案 2 :(得分:0)

尝试将orWhere条件移动到第一个匿名函数中,

return $this->games()
        ->where(function ($query) {
            $query->where('active_player_id', '=', $this->id)
                ->where('stage_name', '<>', 'setup')
            ->orWhere(function ($query) {
                $query->where('active_player_id', '<>', $this->id)
                    ->where('stage_name', '=', 'setup');
        });
        })