php - Laravel 连接表与关系模型返回为 json
问题描述
我有三张桌子:
products
表 (id
,name
)ingredients
表 (id
,ingredient_name
)products_ingredients
表 (product_id
,ingredient_id
)
我在产品中定义了一个关系
public function ingredients(){
return $this->hasMany('App\ProductIngredient','product_id','id');
}
当我列出使用的产品时
$products = Product::where('category_id',$cat->id)->with('ingredients')->get();
我得到这个输出
"products": [{
"id": 1,
"name": "Hesp",
"category_id": 1,
"ingredients": [{
"id": 41,
"product_id": 1,
"ingredient_id": 4,
},
{
"id": 42,
"product_id": 1,
"ingredient_id": 5,
}]
}]
哪个是对的。
我想要的是像这样在成分列表中添加成分名称
"products": [{
"id": 1,
"name": "Hesp",
"category_id": 1,
"ingredients": [{
"id": 41,
"product_id": 1,
"ingredient_id": 4,
"ingredient_name": "some name" // I want to add this field
},
{
"id": 42,
"product_id": 1,
"ingredient_id": 5,
"ingredient_name": "some name" // I want to add this field
}]
}]
我想将此作为 JSON 返回以在 API 中使用,而不是在可以调用其他关系的刀片中使用。
我怎样才能做到这一点?
解决方案
您实施的多对多关系都错了。根据文档:
多对多关系是通过编写一个返回 belongsToMany 方法的结果的方法来定义的。
...
要定义多对多关系的逆向,您需要在相关模型上再次调用 belongsToMany。
class Product extends Model
{
public function ingredients()
{
return $this->belongsToMany('App\Ingredient', 'products_ingredients');
}
}
class Ingredient extends Model
{
public function products()
{
return $this->belongsToMany('App\Product', 'products_ingredients');
}
}
请注意,相关模型是 的第一个参数belongsToMany()
。不需要为简单的数据透视表创建模型。因为您错误地命名了数据透视表,所以必须将其指定为belongsToMany()
. 默认名称是按字母顺序排列的单数模型,即ingredient_product
.
您的输出现在应该看起来像这样,包括ingredients
表中的值,而不是数据透视表。
"products": [{
"id": 1,
"name": "Hesp",
"category_id": 1,
"ingredients": [{
"id": 4,
"ingredient_name": "some name"
},
{
"id": 5,
"ingredient_name": "some name"
}]
}]
推荐阅读
- excel - 无法为 VBA/Excel 逐行绘制折线图
- antlr4 - ANTLR4 - 如何更改源代码并将其取回?
- python - 如果 pip3 在安装后无法正常工作,我该如何解决?
- amazon-web-services - AWS ETL 作业创建一个新列,该列是现有列的子字符串
- javascript - 什么时候必须在 useReducer 中使用扩展运算符?
- shopify - 按产品 SKU 对集合页面进行排序?
- reactjs - 升级reactjs后无法构建三星node_modules/babel-preset-react-app/index.js$0的未知版本4
- pandas - 从具有分组列的数据框中获取随机样本?
- javascript - 调用不带括号的函数?
- python - Python中的MongoDB:从聚合查询的结果中获取特定值