0

This eloquent query filter:

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');
        });

Builds into SQL like this:

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

How do I change the eloquent code to build this query (brackets around the 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')
    ) 
1

3 Answers 3

2

You can achieve that by doing this:

    ->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()
Sign up to request clarification or add additional context in comments.

Comments

0

I don't have an instance of Eloquent to hand to test against just now but would it now be something like this?

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');
        })
    })
;

That is, you put the conditions to be grouped together into an anonymous function on where?

Comments

0

Try moving your orWhere condition into the first anonymous function like this,

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');
        });
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.