【问题标题】:Laravel 5.8 ManyToMany relationship child relation usign foreign key doesn't workLaravel 5.8 使用外键的多对多关系子关系不起作用
【发布时间】:2020-05-13 23:52:47
【问题描述】:

当我调用我的图像资源时,它会从我的模型中返回正确的数据:

图片资源:

     return [
         'id' => $this->id,
         'name' => $this->name,
         'presentation' => $this->presentation->description,
         'slug' =>$this->filename
    ];

图像模型:

    public function presentation()
    {
        return $this->hasOne(ProductPresentation::class, 'id', 'presentation_id');
    }

返回:

{
    "data": [
        {
            "id": 1,
            "name": "White Gold",
            "presentation": "Product x",
            "slug": "products/white-gold.jpg"
        }
}

但是当我调用 manyToMany (Products -> images) 关系时,我只得到 Id 而不是外部关系

    "data": [
        {
            "id": 1,
            "name": "White Gold",
            "price": "€ 10,00",

            "images": [
                {
                    "id": 1,
                    "name": "White Gold",
                    "filename": "products/white-gold.jpg",
                    "presentation_id": 1
                }
            ]
        },

Products 资源调用图像资源,但这不会加载关系(需要 "presentation": "Product x" 而不是 "presentation_id": 1)

使用资源:

        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->formattedPrice,
            'images' => $this->images
        ];

使用模型:

    public function images()
    {
        return $this->belongsToMany(Image::class);
    }

所以问题是如何将关系添加到 belongsToMany(Image::class)

【问题讨论】:

    标签: laravel eloquent foreign-keys many-to-many parent-child


    【解决方案1】:

    尝试改变

    return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->formattedPrice,
            'images' => $this->images
        ];
    

    return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->formattedPrice,
            'images' => YourImageResource::collection($this->images)
        ];
    

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 2021-12-08
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 2020-03-14
      相关资源
      最近更新 更多