sql格式化和提取项目(json)

时间:2018-11-13 08:58:12

标签: php mysql json laravel

因此,基本上我应该根据所有产品的名称进行汇总并列出它们应该不同的名称。 如果我只选择$ [],这将正常工作。表中的项目,但如果要选择带有$ []的所有项目。 我将得到以下内容

行:

[{"brand_name": "Product 1", "brand_id": "4", "quantity": 1}, {"brand_name": "Product 2", "brand_id": "5", "quantity": 3}]

结果:

{
    "brand_id": "[\"4\", \"5\"]",
    "brand_name": "[\"Product 1\", \"Product 2\"]",
    "quantity": 0
}

预期结果:

{
    "brand_id": "4",
    "brand_name": "Product 1",
    "quantity": 1
}
{
    "brand_id": "5",
    "brand_name": "Product 2",
    "quantity": 3
}

查询ELOQUENT:

public function scopegetBasicMeans($query)
{        
    $query->where('type', 1)
        ->join('report_asset', 'report_asset.report_id', '=', 'reports.id')->select(
            DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].name")) as brand_name'), 
            DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].brand_id")) as brand_id'),
            DB::raw('SUM(JSON_EXTRACT(resources, "$[*].quantity")) as quantity')
        )->orderBy('quantity', 'DESC')
            ->groupBy(DB::raw('JSON_EXTRACT(resources, "$[*].name")'));
}

查询原始:

select JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].name")) as brand_name, JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].brand_id")) as brand_id, SUM(JSON_EXTRACT(resources, "$[*].quantity")) as quantity, `reports`.`created_at`, `commercialist_id`, `type` from `reports` inner join `report_asset` on `report_asset`.`report_id` = `reports`.`id` where `reports`.`object_id` = ? and `reports`.`object_id` is not null and `type` = ? and `reports`.`deleted_at` is null group by JSON_EXTRACT(resources, "$[*].name") order by `quantity` desc

基本上,我应该总结所有具有特定名称的项目的质量,并按名称进行分组,这将为我带来独特的结果。 如果我仅从表中选择第一个项目,例如:$ [0] .name [0],而不是多个,这将起作用。 有什么建议吗?

structure

0 个答案:

没有答案