2016-10-17 2 views
0

У меня есть тестовый сайт, где у меня есть таблицы recipes, ingredients и ingredient_uses. Каждый рецепт «использует» ингредиенты в разных количествах и готовят по-разному (например, нарезанный, нарезанный, фарш, тертый), поэтому таблица ingredient_uses отслеживает recipe_id и ingredient_id с другой переменной информацией.laravel отношения назад

Взаимосвязи выглядеть следующим образом:

Рецепт модели:

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'); 
} 

Ингредиент модель:

public function recipe() 
{ 
    return $this->belongsToMany('App\Ingredient'); 
} 

Я думал, что хочу получить отношение от рецепта к таблице ингредиентов, используя ингредиенты в качестве среднего стола. Но 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

Я думаю, вам следует использовать ownToMany в модели Ingredient, 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 и модели ингредиентов.

и можно найти в документации об этом 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; 
Смежные вопросы