[英]Deep relations, *child* relation depends on *great-grandparent* id - with | load - Laravel/Eloquent
我有這個數據庫/模型結構(示例):
*食品類別 -------------- (id, name) - *不相關
食物---------------------- (id, food_category_id, name, ...)
附件組-------- (id, name, ...)
Foods_Accessory Groups - (food_id, acc_group_id) - pivot 表
附件-------------- (id, acc_group_id, name, ...)
Foods_Accessories_Prices - (food_id, accessory_id, price ) - pivot 表
楷模
**foods**
| id | name |
| -------- | ---- |
| 1 | Pork |
| 2 | Eggs |
**accessory_groups**
| id | name |
| -------| -----|
| 1 | Sauce|
foods_accessory_groups
| food_id | accessory_group_id |
| -------- | -------------- |
| 1 | 1 |
| 2 | 1 |
**accessories**
| id | name | acc_group_id |
| -------- | -------------- | - |
| 1 | Mayo | 1 |
| 2 | Ketchup | 1 |
**foods_accessories_prices**
| food_id | accessory_id | price |
| -------- | -------------- | - |
| 1 | 1 | 200 |
| 2 | 1 | 300 |
| 1 | 2 | 250 |
| 2 | 2 | 350 |
代碼示例:
// get all food and relations
$foodCategories = FoodCategory::with([
'foods',
'foods.accessory_groups',
'foods.accessory_groups.accessories',
'foods.accessory_groups.accessories.food_prices' or
'foods.accessory_groups.accessories.food_price' => function ($query) {
// how to filter food prices by great-grandparent relation food (by food_id)
// I know that it can't be done here, but where and how
}
])->get();
配件動態價格取決於食物(曾祖父母關系)。 這個問題的最佳實踐和最優化的解決方案是什么? 后處理或者Laravel Eloquent 都有解決辦法,不太麻煩
food (id = 1, Pork) -> has foods_accessory_groups(id = 1, Sauce) -> has accessories (mayo and ketchup) 其中蛋黃醬價格為 200 ,番茄醬價格為 300。
food (id = 2, Eggs) -... -蛋黃醬價格為 250 ,番茄醬價格為 350。
來自示例的API 響應:
您可以使用whereHas
方法僅查詢與您指定的條件有關系的FoodCategory
模型。
$foodCategories = FoodCategory::query()
->with([
'foods',
'foods.accessory_groups',
'foods.accessory_groups.accessories',
'foods.accessory_groups.accessories.food_prices' or
'foods.accessory_groups.accessories.food_price' => function ($query) {
// load only models from that relationship that match the condition(s)
$query->where(...)
}
])
->whereHas('foods.accessory_groups.accessories.food_price', function ($query) {
// get only categories that have a nested relationship with condition(s)
$query->where(...)
})
->get();
您可以像這樣在您的食品 model 上直接訪問帶有價格的accessories
public function accessories() {
return $this->belongsToMany( Accessory::class )->withPivot('price');
}
或者在你的配件里面做相反的事情 Model
public function foods() {
return $this->belongsToMany( Food::class )->withPivot('price');
}
但由於您沒有直接查詢食物 model,因此您需要正確定義每個 model 的關系,直到您的FoodCategory
model
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.