首页 > 解决方案 > Laravel 连接表与关系模型返回为 json

问题描述

我有三张桌子:

我在产品中定义了一个关系

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 中使用,而不是在可以调用其他关系的刀片中使用。

我怎样才能做到这一点?

标签: phplaraveleloquenteloquent-relationship

解决方案


您实施的多对多关系都错了。根据文档

多对多关系是通过编写一个返回 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"
    }]
}]

推荐阅读