私はrecipes
、ingredients
、およびingredient_uses
のテーブルを持っているテストサイトを持っています。各レシピは、異なる量の成分を「使用」し、異なる方法(例えば、細断し、スライスし、細かく刻み目をつけたもの)を用意しているので、テーブルはrecipe_id
とingredient_id
を別の変数infoで追跡します。laravel relationship backwards
関係は次のようになります。
レシピモデル:
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
の関係をレシピから原料テーブルに欲しいと思っていました。原料テーブルを原料テーブルとして使用しました。 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'成分を思いましたか?なぜそれがhasoneですか? :) –
私は、成分モデル、https://laravel.com/docs/5.3/eloquent-relationships#many-to-manyでbelongsToManyを使うべきだと思います – Borna