从查询生成器返回特定的 JSON 格式
Returning specific JSON format from Query Builder
我正在使用 Query Builder
通过此查询从多个连接表中获取结果:
$products = DB::table('products as p')
->select(
'p.id',
'p.name',
'p.reference',
'p.price',
'i.path',
'i.name'
)
->join('products_r_images as pri', 'pri.product_id', '=', 'p.id')
->join('images as i', 'i.id', '=', 'prd.image_id')
->get();
一个产品可以关联多张图片。
通过上面的查询,我得到了这个结果:
[
{
id: 3,
name: "Test",
reference: "ref-test",
price: 123,
image_path: "product/product-3/",
image_name: "product_1.jpg"
},
{
id: 3,
name: "Test",
reference: "ref-test",
price: 123,
image_path: "product/product-3/",
image_name: "product_2.jpg"
}
]
如您所见,一种产品有两行 returns,而我希望将文档数据 returns 排成一行,类似这样的内容:
[
{
product_id: 3,
name: "Test",
reference: "ref-test",
price: 123,
image_path: "product/product-3/",
image_name:
[
"product_1.jpg", "product_2.jpg"
]
}
]
有没有一种方法可以直接使用查询生成器执行此操作,或者需要其他处理方法?
如果您只想为此使用查询生成器,那么您应该能够:
$products = DB::table('products as p')
->select(
'p.id',
'p.name',
'p.reference',
'p.price',
'i.path',
'i.name'
)
->join('products_r_images as pri', 'pri.product_id', '=', 'p.id')
->join('images as i', 'i.id', '=', 'prd.image_id')
->get()
->groupBy('id')
->map(function ($products) {
$product = $products->first();
$product->image_name = $products->pluck('image_name');
return $product;
});
希望对您有所帮助!
我正在使用 Query Builder
通过此查询从多个连接表中获取结果:
$products = DB::table('products as p')
->select(
'p.id',
'p.name',
'p.reference',
'p.price',
'i.path',
'i.name'
)
->join('products_r_images as pri', 'pri.product_id', '=', 'p.id')
->join('images as i', 'i.id', '=', 'prd.image_id')
->get();
一个产品可以关联多张图片。
通过上面的查询,我得到了这个结果:
[
{
id: 3,
name: "Test",
reference: "ref-test",
price: 123,
image_path: "product/product-3/",
image_name: "product_1.jpg"
},
{
id: 3,
name: "Test",
reference: "ref-test",
price: 123,
image_path: "product/product-3/",
image_name: "product_2.jpg"
}
]
如您所见,一种产品有两行 returns,而我希望将文档数据 returns 排成一行,类似这样的内容:
[
{
product_id: 3,
name: "Test",
reference: "ref-test",
price: 123,
image_path: "product/product-3/",
image_name:
[
"product_1.jpg", "product_2.jpg"
]
}
]
有没有一种方法可以直接使用查询生成器执行此操作,或者需要其他处理方法?
如果您只想为此使用查询生成器,那么您应该能够:
$products = DB::table('products as p')
->select(
'p.id',
'p.name',
'p.reference',
'p.price',
'i.path',
'i.name'
)
->join('products_r_images as pri', 'pri.product_id', '=', 'p.id')
->join('images as i', 'i.id', '=', 'prd.image_id')
->get()
->groupBy('id')
->map(function ($products) {
$product = $products->first();
$product->image_name = $products->pluck('image_name');
return $product;
});
希望对您有所帮助!