我有這 3 張表Apparel、Outfit、ApparelOutf??it(下面的表結構示例)。我想使用 ApparelOutf??it 資料透視表中的一組服裝 ID 來檢查服裝是否存在。服裝ids陣列應該和服裝相關的服裝ids完全相同,不多不少。我該怎么做?
-- Apparel --
id | name
-- Outfit --
id | is_favorite
-- ApparelOutfit -- (pivot table)
apparel_id | outfit_id
uj5u.com熱心網友回復:
根據您通過評論輸入
int OUTfit 模型我有這個。公共功能服裝(){回傳$this->belongsToMany(Apparel::class)->withTimestamps()->as('apparel_outfit')->orderByPivot('apparel_id');}
你可以試試
//Say you have the following apparel ids
$apparelIds = [1,2,3];
$outfits = Outfit::query()
->whereHas(
'apparels',
fn($query) => $query->whereIn('id', $apparelIds),
'=',
count($apparelIds)
)
/** If you want to get the records */
->get();
/** If you just want how many outfits exist for the given $apparelIds
* ->count();
*/
上面的查詢將獲取與這些$apparelIds相關聯的服裝記錄——不多不少
例如:
假設裝備 1 的服飾 ID 為 [1,2,3],裝備 2 的服飾 ID 為 [1,2,3,4]
然后只回傳裝備1
Laravel Docs - Eloquent 關系 - 查詢關系是否存在
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485940.html
