0

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();
Piny1989
  • 1
  • 3
  • 1
    That should work. What happens when you try? Try logging the queries (in mysql, `SET general_log = 'on';`, for Laravel, log `\DB::getQueryLog();`. – aynber Nov 28 '16 at 22:11
  • The query looks fine to me. In this example id 184 should not be in there. http://pastebin.com/QsEGMyZx – Piny1989 Nov 28 '16 at 22:24
  • Try dumping the tags for each one as well. – aynber Nov 28 '16 at 22:27
  • Id 184 is the one I want to exclude. It has both tags. See http://pastebin.com/VGfMx1mj Is this the problem? It has the tag I am including, but also the tag I want to exclude – Piny1989 Nov 28 '16 at 22:31

0 Answers0