【发布时间】: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