我有以下代码返回与$ included数组中的标记关联的所有文件,这样可以正常工作。
FileObject::whereHas('tags', function($q) use ($included){
$q->WhereIn('name', $included);
})->get())
现在我也要排除某些标签,所以我尝试下面的代码似乎不起作用。
FileObject::whereHas('tags', function($q) use ($included,$excluded){
$q->WhereIn('name', $included)
->WhereNotIn('name', $excluded);
})->get())
如何创建此查询?
感谢。
修改1
返回的准备好的SQL字符串如下
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 (?)
)
但我需要的是这个
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 (?)
)
)
解决
在我的情况下,这按预期工作
$files = FileObject::whereHas('tags', function($q) use ($included){
$q->whereIn('name', $included);
})->whereDoesntHave('tags', function($q) use ($excluded){
$q->whereIn('name', $excluded);
})->get();