您好我有三张桌子
食谱
id | name
1 | Spaghetti
食品
id | name
1 | tomato
2 | banana
成分食谱
id | idRecipe | idFood
1 | 1 | 1
2 | 1 | 2
如何从食谱我可以通过表格成分食谱获得所有名称食物?
在模型食谱中我尝试使用Eloquent关系有很多通过但它不起作用
public function NameFood()
{
return $this->hasManyThrough('App\Food', 'App\IngredientRecipes', 'idRecipe', 'id', 'idFood');
}
答案 0 :(得分:1)
在您的食谱模型中,您可以创建belongsToMany关系。
class Recipe extends Model
{
public function foods()
{
return $this->belongsToMany(
App\Food::class,
'ingredient_recipes',
'idRecipe',
'idFood',
);
}
}
现在你可以从食谱中取出所有食物:
$all_foods = $my_recipe->foods;
$only_names = $my_recipe->foods->pluck('name');
最好调用你的外键,如:" tablename_id"例如:" food_id"," recipe_id"。它是laravel关系中的自动命名。
我希望你的答案还可以。祝你好运。