【发布时间】:2018-11-14 11:57:57
【问题描述】:
在从数据库中选择 json 数据时,我遇到了问题。 有没有办法按索引提取数据。
我需要这个,因为我想按 json 项目的名称求和和分组,如果我从数组中提取第一个项目,我可以做到这一点:
DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[0].name[0]")) as brand_name'),
DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[0].brand_id[0]")) as brand_id'),
DB::raw('SUM(JSON_EXTRACT(resources, "$[0].quantity[0]")) as quantity')
然后我会按 $[0].name[0] 分组,我会得到独特的结果。
存储在sql中的数据:
[[{\"name\": \"Product 1\", \"brand_id\": \"2\", \"quantity\": 2},
{\"name\": \"Product 2\", \"brand_id\": \"3\", \"quantity\": 1}],
[{\"name\": \"Product 3\", \"brand_id\": \"1\", \"quantity\": 2},
{\"name\": \"Product 1\", \"brand_id\": \"2\", \"quantity\": 5}],
[{\"name\": \"Product 4\", \"brand_id\": \"4\", \"quantity\": 2},
{\"name\": \"Product 5\", \"brand_id\": \"5\", \"quantity\": 5}]]
如果您明白我的意思,我应该将所有同名产品的数量相加,并得到唯一的响应,而不是多个同名商品。 例如应该只有一个
产品 1,总数量为 7。
【问题讨论】: