Laravel eloquent 使用 OR 查询建筑物

Laravel eloquent query building using OR

这个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')
    ) 

你可以这样做:

    ->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()

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

return $this->games()
    ->where(function ($query) {
        $query->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');
        })
    })
;

也就是你把要分组的条件放到where上的一个匿名函数里?

尝试将您的 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');
        });
        })