2016-10-17 4 views
0

私はrecipesingredients、およびingredient_usesのテーブルを持っているテストサイトを持っています。各レシピは、異なる量の成分を「使用」し、異なる方法(例えば、細断し、スライスし、細かく刻み目をつけたもの)を用意しているので、テーブルはrecipe_idingredient_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 

は、私が使用する必要があり、より適切な関係がありますか?

+0

待ち - 私は 'Ingredient_Use'べき' belongsTo'成分を思いましたか?なぜそれがhasoneですか? :) –

+0

私は、成分モデル、https://laravel.com/docs/5.3/eloquent-relationships#many-to-manyでbelongsToManyを使うべきだと思います – Borna

答えて

0

における成分モデル

class Ingredient extends Model 
{ 


    public function recipe(){ 

      return $this->belongsToMany(Recipe::class, 'ingredient_uses', 'ingredient_id', 'recipe_id'); 
    } 

} 

他のモデルは、空のthatsはレシピのモデルとIngredientモデル内の任意の関数は存在しないだろう意味になります。

uがこの https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

2

最初のものについてのドキュメントを参照してくださいすることができます - あなたはIngredient_Useモデルを必要としません。モデル例:追加のフィールドの例に

class Ingredient extends Model 
{ 
    /** 
    * @var string 
    */ 
    protected $table = 'ingredients'; 

    /** 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function recipes() 
    { 
     return $this->belongsToMany(Recipe::class, 'recipes_ingredients', 'ingredient_id'); 
    } 
} 




class Recipe extends Model 
{ 
    /** 
    * @var string 
    */ 
    protected $table = 'recipes'; 

    /** 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function ingredients() 
    { 
     return $this->belongsToMany(Ingredient::class, 'recipes_ingredients', 'recipe_id')->withPivot('additional', 'fields'); 
    } 
} 

アクセス

$recipe->pivot->additional;