2017-05-06 71 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