2016-10-17 77 views
0

我有一個測試網站,我有一個recipes,ingredientsingredient_uses表。每個食譜「使用」不同數量的成分並且以不同方式進行準備(例如,切碎,切片,切碎,磨碎),因此ingredient_uses表跟蹤recipe_idingredient_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 

有,我應該用更合適的關係?

+0

等待 - 我想'Ingredient_Use'應該'belongsTo'成分?爲什麼它有一個? :) –

+0

我想你應該在Ingredient模型中使用belongsToMany,https://laravel.com/docs/5.3/eloquent-relationships#many-to-many – Borna

回答

0

成分模型等

class Ingredient extends Model 
{ 


    public function recipe(){ 

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

} 

車型將是空的,多數民衆贊成意味着就不會有Recipe模型和Ingredient模型內部的任何功能。

ü可以看到文檔關於本 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;