问题描述
我有两个表:categories
和videos
,然后我有一个数据透视表,因为它是一个belongsToMany关系.
I have two tables: categories
and videos
, I then have a pivot table for these as it's a belongsToMany relationship.
我想做的是将所有视频中没有单个实例归入多个类别之一.
What I'm trying to do is get all of the videos where there isn't a single instance of the video being in one of many categories.
例如
- 视频1属于类别1、2和3.
- 视频2属于类别1和3.
- 视频3属于类别1.
我想获取不在2类或3类中的视频,这意味着它将返回3类视频.
I want to get the video which is NOT in category 2 or 3, meaning this will return Video 3.
到目前为止,我一直在尝试,但没有得到预期的结果,这是因为仍在视频1和2中找到了另一行,就像它们在类别1中一样:
What I've tried so far, which doesn't give the intended result, this is because another row is still found for Video 1 and 2, as they are in Category 1:
Video::whereHas('categories', function($query) {
$query->whereNotIn('category_id', [2,3]);
})->take(25)->get();
从中填充的查询是:
select * from `videos` where exists (select * from `categories` inner join
`category_video` on `categories`.`id` = `category_video`.`category_id` where
`videos`.`id` = `category_video`.`video_id` and `category_id` != ? and
`category_id` != ? and `categories`.`deleted_at` is null) and `videos`.`deleted_at`
is null order by `created_at` desc limit 25
推荐答案
您可以使用Eloquent的 whereDoesntHave()约束来获得所需的内容:
You can use Eloquent's whereDoesntHave() constraint to get what you need:
// get all Videos that don't belong to category 2 and 3
Video::whereDoesntHave('categories', function($query) {
$query->whereIn('id', [2, 3]);
})->get();
这篇关于Laravel属于ToMany,其中没有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!