我有一个终点,当前的响应如下所示,当我们使用groupBy()查询时,它只返回一行,但是如何获得一个带有隐藏分组值的嵌套json。
//controller
public function products()
{
$get_products = Product::groupBy('name')
->get();
$data = [
'data' => $get_products
];
return Response::json(
$data_with_status = array_merge($this->respondSuccess('query successfull'), $data)
);
}
//json response
{
"status_code": 200,
"status_message": "query successfull",
"data": [
{
"id": 1,
"name": "onion",
"proportion": "500 gm",
"mrp": "25",
"price": "22",
"status": "1"
}
]
}
预期结果如下,是否有查询来实现此目的,
{
"status_code": 200,
"status_message": "query successfull",
"data": [
{
"id": 1,
"name": "onion",
"proportion": {
"0": "500 gm",
"1": "1 kg",
}
"mrp": "25",
"price": "22",
"status": "1"
},
{
"id": 2,
"name": "tomato",
"proportion": "500 gm"
"mrp": "20",
"price": "15",
"status": "1"
}
]
}
数据库架构如下
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('proportion');
$table->string('mrp');
$table->string('price');
$table->enum('status', ['available','unavailable']);
$table->timestamps();
$table->softDeletes();
});
要从产品表分组的样本数据
id name proportion mrp price status
1 onion 500 gm 25 22 1
2 onion 1 kg 50 44 1
3 tomato 500 gm 20 15 1
如果产品名称相同,则表示如果产品具有多个比例,我想对产品进行分组并将比例合并到json中,如上面预期的json结果所示。
谢谢
答案 0 :(得分:1)
使用group_cancat()
-
$get_products = Product::select('id','name','mrp','price','status',DB::raw('group_concat(proportion)'))
->groupBy('name')->get();