2017-03-09 158 views
7

在我的應用程序中,我已更新從one-to-manymany-to-many的關係,並試圖找出一種方法來保持關聯的功能。Laravel雄辯多對多查詢WhereIn

比方說,我有兩個相關的表,例如,狗和業主。如果我有一羣業主,並且我正在努力爲這些業主獲得一張ID列表,我該怎麼做呢?

類似的問題在這裏問: https://laracasts.com/discuss/channels/laravel/getting-many-to-many-related-data-for-an-array-of-elements

所以,我該如何獲得Dog模式,使Owner是一個數組?

$associatedDogs = Dog::whereIn('owner_id',$ListOfOwners)->get();相同的是One-To-Many關係,但是關於Many-to-Many

回答

9

使用whereHas()方法:

$dogs = Dog::whereHas('owners', function($q) use($ownerIds) { 
    $q->whereIn('id', $ownerIds); 
})->get(); 
+0

我應該選擇'whereHas'過'with'?他們在這種情況下有什麼區別?它甚至有什麼區別? –

+0

沒關係,我在這裏找到了解釋:http://stackoverflow.com/a/30232227/2012740 –

+0

@AngelinCalu是的,'with()'不適合你,因爲它加載關係數據。 –

1

嘗試

$associateDogs = Dog::with(['owners' => function($query) use ($listOfOwners) { 
    $query->whereIn('id', $listOfOwners); 
}])->get();