2017-05-06 105 views
0

我有两个表:categoriesvideos,我再对这些数据透视表,因为它是一个belongsToMany关系。Laravel belongsToMany其中不具有

我想要做的就是让所有的视频中没有视频在许多类别中的一个是单个实例。

例如

  • 视频1是1类,2和3
  • 视频2为1类和第3
  • 视频3是第1类。

我想要得到的视频这是不是在2类或3个,意味着这将返回视频3.

我到目前为止已经试过,不给预期的结果,这是因为另一行仍发现视频1 2,因为它们在第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 
+0

一个肮脏的解决方案的一个位将在两个类别中不使用语句时使用2。 – milo526

+0

是的,我认为,但我从字面上有大约100类别的过滤,我想我能永远的foreach? – Karl

+0

原来,即使是在哪里会返回相同的地方,不是吗? – Karl

回答

0

你可以用雄辩的whereDoesntHave()约束得到你需要的东西:

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

这样做很不幸,这仍然返回相同的结果:/ – Karl

+0

它不能给你同样的结果,因为它是一个不同的查询,你提取的视频至少有一个类别为2和3以外的其他类别。此视频给出的视频没有ID为2或3的类别。 –

+0

很明显,这不是确切的结果,但它仍然会返回属于第2类或第3类的视频,因为它在类别1. – Karl