
[英]Laravel Relationship with condtion on foreign key (toggle foreign key on relation)
[英]Laravel 5.8 ManyToMany relationship child relation usign foreign key doesn't work
当我调用我的图像资源时,它会从我的模型中返回正确的数据:
图片资源:
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)
尝试改变
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)
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.