Laravel 加入 table 与关系模型 return 作为 json

Laravel joining table with relation model return as json

我有三个table:

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

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 
    }]
}]

我想 return 这个作为 JSON 在 API 中使用,而不是在 blade 中我可以调用其他关系。

我怎样才能做到这一点?

你实现的多对多关系全错了。每 the documentation:

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method.

...

To define the inverse of a many-to-many relationship, you place another call to belongsToMany on your related model.

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() 的第一个参数。不需要为简单的枢轴创建模型 table。因为你错误地命名了主元 table,它必须被指定为 belongsToMany() 的第二个参数。默认名称是按字母顺序排列的单数模型,即 ingredient_product.


您的输出现在应该看起来像这样,包括来自 ingredients table 的值,而不是枢轴 table.

"products": [{
    "id": 1,
    "name": "Hesp",
    "category_id": 1,
    "ingredients": [{
        "id": 4,
        "ingredient_name": "some name"
    },
    {
        "id": 5,
        "ingredient_name": "some name"
    }]
}]