[
{
"agent_id": "D01",
"amount": "2"
},
{
"agent_id": "D01",
"amount": "2"
},
{
"agent_id": "A01",
"amount": "1"
},
{
"agent_id": "A01",
"amount": "1"
},
]
[
{
"agent_id": "D01",
"amount": "4"
},
{
"agent_id": "A01",
"amount": "2"
},
]
Hello, there is an original dataset with 4 collections as shown above. I was try to transform the data with group by agent_id
and sum of the amount
.
I was plan to using sub query likes select agent_id, sum(amount) from (Dataset) group by agent_id
, however I have no idea how to achieve it in laravel sub query. Can anyone guide me or and provide some suggestion. Appreciate it.
If the data is provided via a dataset or an api call then you can use Laravel Collection methods to manipulate and get the desired output
//Assuming that the data is in array format
$output = collect($data)
->groupBy('agent_id')
->map(
fn($records, $agent) => ['agent_id' => $agent, 'amount' => $records->sum('amount')]
)
->values()->all();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.