我有三个表:
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"
}]
}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句