简体   繁体   中英

Multiple conditions on Eloquent query

I can't seem to be able to Google a solution that I can understand how to apply to this issue... I have the following query:

$files = EvidenceFile::where('owner_id', $user_id)->orWhere('public', '1')->whereNotIn('id', $exclude_file_ids)->get();

What I'm hoping to get is a list of files matching the 'owner_id' or where their 'public' flag is 1, but I don't want any rows whose 'id' matches any in the array '$exclude_file_ids`.... Does that make sense?

The query I'm using above is returning a list of files as if it's ignoring the 'whereNotIn' clause...

I've also tried:

$results = EvidenceFile::where('owner_id', $user_id)->orWhere('public', '1');
$results = $results->whereNotIn('id', $exclude_file_ids);
$files = $results->get();

But that is returning everything too. How should I write this query for it to work?

Take a look at your search conditions:

NOT in excluded ids
AND (
   public OR belongs to user
)

Now you have your orWhere at the outer level, so you are getting all public items, regardless of the excluded ids (in other words, AND takes precedence over OR, so the OR is 'applied' afterwards).

So, I'd suggest you group your where clauses:

$results = EvidenceFile::whereNotIn('id', $exclude_file_ids)
               ->where(function ($query) use ($user_id) {
                   $query->where('owner_id', $user_id)
                     ->orWhere('public', '1');
               })
               ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM