Laravel将单独的记录合并为一个记录

时间:2018-11-22 22:00:59

标签: sql laravel eloquent

嗨,我有3条记录,我想将它们合并为一条json记录。例如,我正在执行以下查询:

$shopList = $inventory
->select('shop_code', 'barcode', 'product_code', 'matrix_level_code_1',
'matrix_level_code_2', 'matrix_level_code_3', 'qty')->get();
return response()->json($shopList);

它返回:

{
    "shop_code": "001",
    "barcode": "505455553989",
    "product_code": "ANXA-683B-V148",
    "matrix_level_code_1": "1Z",
    "matrix_level_code_2": "0",
    "matrix_level_code_3": "",
    "qty": 3
 }

但是我希望将其显示为:

{
   "shop_code": "001",
   "barcode": "505455553989",
   "sku": "ANXA-683B-V148-1Z-0",
   "qty": 3
}

这可能吗?谢谢

1 个答案:

答案 0 :(得分:0)

您可以在mysql上使用concat,以便将更多结果合并为一个,并使用自定义键对其进行别名。

$shopList = $inventory->select([
    'shop_code',
    'barcode',
    DB::raw('concat(product_code, "-", matrix_level_code_1, "-", matrix_level_code_2, "-", matrix_level_code_3) as sku'),
    'qty'
])->get();

确保将use DB;放在顶部。