我有一個測試網站,我有一個recipes
,ingredients
和ingredient_uses
表。每個食譜「使用」不同數量的成分並且以不同方式進行準備(例如,切碎,切片,切碎,磨碎),因此ingredient_uses
表跟蹤recipe_id
和ingredient_id
以及其他變量信息。laravel relationship backwards
的關係是這樣的:
Recipe模型:
public function ingredients()
{
return $this->hasManyThrough('App\Ingredient', 'App\IngredientUse');
}
public function ingredientUses()
{
return $this->hasMany('App\IngredientUse');
}
Ingredient_Use型號:
public function ingredient()
{
return $this->hasOne('App\Ingredient');
}
public function recipe()
{
return $this->belongsTo('App\Recipe');
}
Ingredient模型:
public function recipe()
{
return $this->belongsToMany('App\Ingredient');
}
我以爲我想從配方到配料表中使用hasManyThrough
關係,使用ingredient_uses作爲中間表。但是SQL是錯誤的:
SELECT `ingredients`.*, `ingredient_uses`.`recipe_id`
FROM `ingredients`
INNER JOIN `ingredient_uses`
ON `ingredient_uses`.`id` = `ingredients`.`ingredient_use_id`
WHERE `ingredient_uses`.`recipe_id` = 1
這是我認爲我想:
SELECT `ingredients`.*, `ingredient_uses`.`recipe_id`
FROM `ingredients`
INNER JOIN `ingredient_uses`
ON `ingredient_uses`.`ingredient_id` = `ingredients`.`id`
WHERE `ingredient_uses`.`recipe_id` = 1
有,我應該用更合適的關係?
等待 - 我想'Ingredient_Use'應該'belongsTo'成分?爲什麼它有一個? :) –
我想你應該在Ingredient模型中使用belongsToMany,https://laravel.com/docs/5.3/eloquent-relationships#many-to-many – Borna