I have the following code that returns all the files associated with a tag from the $included array, which works fine.
FileObject::whereHas('tags', function($q) use ($included){
$q->WhereIn('name', $included);
})->get())
Now I want to exclude certain tags too, so I tried this code below which does not seem to work.
FileObject::whereHas('tags', function($q) use ($included,$excluded){
$q->WhereIn('name', $included)
->WhereNotIn('name', $excluded);
})->get())
How do I create this query?
Thanks.
Edit 1
The returned prepared SQL String is the following
select * from `fileobjects`
where exists (
select * from `tags`
inner join `taggables` on `tags`.`id` = `taggables`.`tag_id`
where `taggables`.`taggable_id` = `fileobjects`.`id`
and `taggables`.`taggable_type` = ?
and `name` in (?) and `name` not in (?)
)
But what I need is this
select * from `fileobjects`
where
(
exists (
select * from `tags`
inner join `taggables` on `tags`.`id` = `taggables`.`tag_id`
where `taggables`.`taggable_id` = `fileobjects`.`id`
and `taggables`.`taggable_type` = "App\\FileObject"
and `name` in (?)
)
)
and
(
not exists (
select * from `tags`
inner join `taggables` on `tags`.`id` = `taggables`.`tag_id`
where `taggables`.`taggable_id` = `fileobjects`.`id`
and `taggables`.`taggable_type` = "App\\FileObject"
and `name` in (?)
)
)
Solved
Well in my case this works as expected
$files = FileObject::whereHas('tags', function($q) use ($included){
$q->whereIn('name', $included);
})->whereDoesntHave('tags', function($q) use ($excluded){
$q->whereIn('name', $excluded);
})->get();