Any suggestions after the weekend?
Apr 22, 2022
5
Level 2
How to get percent of order statistic by count with groupBy
Hello!
I'm trying to get some data with statistic about order statuses. Currently receives some data with count of specific status grouped by shop_id and status, before that, gets the records filtered by spatie query builder e.g. a date range.
In addition to the status object, apart from wanting to add a percentage of quantity relative to other statuses but I don't know how I can do get all statuses count.
This is my code and and what I would like to receive
$orders = (new GetFilterSortOrders())();
$collection = $orders
->groupBy('shop_id')
->map(function ($row) {
return [
'orderable_name' => $row[0]->orderable_type,
'shop_id' => $row[0]->shop_id,
'statuses' => $row->groupBy('status')->map(function ($status) {
return [
'count' => $status->count(),
'percent' => ($status->count() / $allStatusesCount) * 100
];
})
];
})
->paginate(request('perPage') ?? 15);
return OrderStatisticResource::collection($collection);
Thanks for help!
Level 5
@Sinres inside you first map , you can probably do this:
->map(function ($row) {
$allStatusesCount = $row->count();
return [
'orderable_name' => $row[0]->orderable_type,
'shop_id' => $row[0]->shop_id,
'statuses' => $row->groupBy('status')->map(function ($status) use ($allStatusesCount) {
return [
'count' => $status->count(),
'percent' => ($status->count() / $allStatusesCount) * 100
];
})
];
})
1 like
Please or to participate in this conversation.