Matt Larsuma
Matt Larsuma

Reputation: 1519

Laravel 5.7 eloquent query with multiple wheres and a whereNotIn

I'm attempting to execute a query that gets a data set based on a user id matching two possible columns and a workflow_state not matching two values. My attempt is here:

$usersBugs = Bug::where('assigned_user_id', $user->id)
                ->orWhere('reported_by', $user->id)
                ->whereNotIn('workflow_state', ['closed', 'rejected'])
                ->get();

It is returning a "bug" with a rejected workflow_state. I'm guessing it is executing the whereNotIn as an or? How would I refactor this to execute that the bug cannot be in either of those two states (no matter what) and it can match either the assigned_user_id OR the report_by. I tried leading with the whereNotIn:

$usersBugs = Bug::whereNotIn('workflow_state', ['closed', 'rejected'])
                ->where('assigned_user_id', $user->id)
                ->orWhere('reported_by', $user->id)
                ->get();

Either way it is returning a matched bug based on the assigned_user_id, despite the fact that the workflow_state is rejected.

Upvotes: 0

Views: 453

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111859

You should wrap where .. orWhere into additional closure:

$usersBugs = Bug::where(function($q) {
  $q->where('assigned_user_id', $user->id)
                    ->orWhere('reported_by', $user->id)
})->whereNotIn('workflow_state', ['closed', 'rejected'])->get();

Upvotes: 1

Kyslik
Kyslik

Reputation: 8385

You may try this:

$model->whereNotIn(...)->where(function($query) use ($user) {
   $query->where('assigned_user_id', $user->id)->orWhere('reported_by', $user->id);
})->get();

Upvotes: 2

Related Questions