laravel Laravel属于许多没有其中之一的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43821403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:55:28  来源:igfitidea点击:

Laravel belongsToMany where doesn't have one of

phpmysqllaraveleloquenthas-and-belongs-to-many

提问by Karl

I have two tables: categoriesand videos, I then have a pivot table for these as it's a belongsToMany relationship.

我有两个表:categoriesand videos,然后我有一个数据透视表,因为它是一个belongsToMany关系。

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.

我想要做的是获取所有视频,其中没有一个视频实例属于多个类别之一。

e.g.

例如

  • Video 1 is in category 1, 2 and 3.
  • Video 2 is in category 1 and 3.
  • Video 3 is in category 1.
  • 视频 1 属于类别 1、2 和 3。
  • 视频 2 属于类别 1 和类别 3。
  • 视频 3 属于类别 1。

I want to get the video which is NOT in category 2 or 3, meaning this will return Video 3.

我想获得不在类别 2 或 3 中的视频,这意味着这将返回视频 3。

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:

到目前为止我已经尝试过,但没有给出预期的结果,这是因为视频 1 和 2 仍然存在另一行,因为它们在类别 1 中:

Video::whereHas('categories', function($query) {
    $query->whereNotIn('category_id', [2,3]);
})->take(25)->get();

The query populated from this is:

由此填充的查询是:

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

回答by jedrzej.kurylo

You can use Eloquent's whereDoesntHave()constraint to get what you need:

您可以使用EloquentwhereDoesntHave()约束来获取您需要的内容:

// get all Videos that don't belong to category 2 and 3
Video::whereDoesntHave('categories', function($query) {
  $query->whereIn('id', [2, 3]);
})->get();