So basically I should sum and list all products based on their name they should differ. This would work properly if I only selected the $[]. item from the table but if I were to select all items with $[]. I will get the following
ROW:
[{"brand_name": "Product 1", "brand_id": "4", "quantity": 1}, {"brand_name": "Product 2", "brand_id": "5", "quantity": 3}]
RESULT:
{
"brand_id": "[\"4\", \"5\"]",
"brand_name": "[\"Product 1\", \"Product 2\"]",
"quantity": 0
}
EXPECTED RESULT:
{
"brand_id": "4",
"brand_name": "Product 1",
"quantity": 1
}
{
"brand_id": "5",
"brand_name": "Product 2",
"quantity": 3
}
QUERY 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")'));
}
QUERY RAW:
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
Basically I should sum the quality of all items with specific name and group them by their name which will get me the unique results. This would work if i were to select only first item from the table for example: $[0].name[0] but not on multiple. Any suggestions?