我就是这样的
[ { “名称产品”:“iphone”, “产品ID”:1, “标价”:100000, “图像路径”:“iphone.png” }, [ { “ID集合”:5, "NameCollection": "电话", "描述": "我的描述", } ], { “名称产品”:“三星”, “产品ID”:2, “标价”:379000, “图像路径”:“三星.png” }, [ { “ID集合”:5, "NameCollection": "电话", "描述": "我的描述", } ],
但我想要这样:
{
"IDCollection": 5,
"NameCollection": "Phone",
"ProductList": [
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 100000,
"ImagePath": "samsung.png"
},
]
}
这是我的代码:
public function show(int $id)
{
$product=[];
$product_collection = CollectionProduct::where('IDCollection',$id)->get();
$collection = Collection::where('IDCollection',$id)->get();
foreach ($product_collection as $items) {
$x = Product::select('NameProduct','IDProduct','ListPrice')->find($items['IDProduct']);
$x->ImagePath = ProductImage::where('IDProduct',$items['IDProduct'])->first()['Path'];
array_push($product, $x,$collection);
}
return response()->json($product);
}
知道怎么做吗?
您可以使用Eager Loading来获取CollectionProduct的关系。 https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
为了帮助您编写代码,我需要查看您与数据库的关系,但我认为这可以帮助您:
public function show(int $id)
{
$product_collection = CollectionProduct::with('collection.product.productImage')
->where('IDCollection',$id)
->get();
return response()->json($product_collection);
}