laravel - laravel 5.7 获得多对多关系结果的正确方法
问题描述
我正在学习 laravel 框架,我有一个非常简单的问题:
我有三张桌子:
食物表:
foods
--------------
id | name
成分表:
ingredients
---------------
id, | name
数据透视表:
food_ingredient
---------------
food_id | ingredient_id
在模型中,我有“belongsToMany”方法:
食品型号:
public function ingredients(){
return $this->belongsToMany('App\Models\Ingredient');
}
成分型号:
public function foods(){
return $this->belongsToMany('App\Models\Food');
}
FoodsController(索引):
$foods = Food::all();
foreach($foods as $food){
$food->ingredients = Ingredient::join('food_ingredient','food_ingredient.id','=','ingredients.id')
->where('food_ingredient.food_id',$food->id)->get();
}
我想获取每种食物的成分信息(直到现在只是名称),这个查询(那个在 foreach 循环中)可以做到,但我不确定我是否以正确的方式做。我没有使用belongsToMany 关系所以......我的理解一定有问题。
我怎样才能得到成分的名称?
直到知道这些名字都可以,但我会添加第三个表“过敏原”,它很快就会成为数据透视表“allergen_ingredient”。然后,我必须得到每种食物、它们的成分,以及每种成分的过敏原。所以,我想从现在开始做好。
先感谢您。
解决方案
食物模型
class Food extends Model
{
protected $table = 'foods';
protected $primaryKey = 'food_id';
public $incrementing = TRUE;
public $timestamps = FALSE;
protected $fillable = [
'food_name'
];
public
function ingredients()
{
return $this->belongsToMany(Ingredient::class, 'food_ingredients', 'food_id', 'ingredient_id');
}
}
成分模型
class Ingredient extends Model
{
protected $table = 'ingredients';
protected $primaryKey = 'ingredient_id';
public $incrementing = TRUE;
public $timestamps = FALSE;
protected $fillable = [
'ingredient_name'
];
public
function foods()
{
return $this->belongsToMany(Food::class, 'food_ingredients', 'ingredient_id', 'food_id');
}
}
你可以这样称呼它:
$foods = Food::all();
foreach( $foods as $food )
{
foreach( $food->ingredients as $ingredient )
{
echo $ingredient->ingredient_name . " <br>";
}
}
food_ingredients 是数据透视表名称
推荐阅读
- python-3.x - 在 RTL 语言风格中,Psychopy 字符空间不相等
- r - 如何仅对具有相同值的序列进行分组
- java - 如何在 HTTP POST/GET 中发送空参数
- javascript - Javascript 函数不能正常工作。无法将属性“onclick”设置为 null
- node.js - Express.js 页面刷新两次打印内容两次
- android - Android“泄漏上下文”错误
- tcp - 在 wso2 ESB 上通过 TCP 发送数据
- swift - 在 swift 中使用 RegExp 降低浮点精度
- gradle - 带有 API 密钥的 Gradle 和 Artifactory 插件
- wpf - System.Byte[]' 不是属性 ImageSource 的有效值