sql json格式和汇总

时间:2018-11-02 08:48:42

标签: php mysql json laravel

所以基本上我有一个函数,它以这种格式从数据库返回json数据:

"meanings": [
    "[
    {\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 4},
    {\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 1},
    {\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 1},
    {\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 4},
    {\"name\": \"Product 2\", \"product_id\": \"2\", \"quantity\": 4},
    {\"name\": \"Product 3\", \"product_id\": \"3\", \"quantity\": 4},
    {\"na]"
]

我要实现的是对具有相同品牌ID的所有产品的数量求和,得到以下结果:

"meanings": [
    "[
    {\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 10},
    {\"name\": \"Product 2\", \"product_id\": \"2\", \"quantity\": 4},
    {\"name\": \"Product 3\", \"product_id\": \"3\", \"quantity\": 4},
    {\"na]"
]

我通过编写以下内容(纯PHP)实现了它的作用,但问题是这是API。 多次打电话并不是最好的选择,它最终将开始引起问题。

$data = [];
$pId = [];
$objects = $this->reports()->getBasicMeans($this->id)->get();
foreach($objects as $object)
{
    $newData = json_decode($object);
    $data[$newData->product_id]['name'] = $newData->name;
    $data[$newData->product_id]['product_id'] = $newData->product_id;
    if (!in_array($newData->product_id, $pId)) {
        $pId[] = $newData->product_id;
        $data[$newData->product_id]['quantity'] = $newData->quantity;
    } else {
        $data[$newData->product_id]['quantity'] += $newData->quantity;
    }
}

$json['meanings'] = json_encode($data);

这是向我返回json的查询。有没有一种方法可以修改查询,而无需使用php函数来实现我想要的结果?

/**
 * Get basic means for the specified object.
 *
 * @param [type] $query
 * @param [type] $object
 * @return void
 */
public function scopegetBasicMeans($query, $object = null)
{
    $query->where('object_id', $object)->where('type', 1)
        ->join('report_asset', 'report_asset.report_id', '=', 'reports.id')->select(
            DB::raw(
                'SUM(JSON_EXTRACT(report_asset.resources, "$.quantity")) as amount'
            )
        )->groupBy(DB::raw('JSON_EXTRACT(report_asset.resources, "$.name")'));
}

我正在使用mysql 5.7

查询:

select SUM(JSON_EXTRACT(report_asset.resources, \"$.quantity\")) as amount 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 `object_id` = ? and `type` = ? and `reports`.`deleted_at` is null group by JSON_EXTRACT(report_asset.resources, \"$.name\")

0 个答案:

没有答案