Reputation: 983
I have an object that consists of multiple data as controlNumber
each controlNumber
has shipment.qty
what I want is to total the qty
of each same controlNumber
and display one controlNumber
with total qty.
collection is below
"collection": [
{
"id": 983,
"controlNumber": 4498818,
"ItemNumber": "PS2W12077",
"shipment": {
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": 1638
}
},
{
"id": 982,
"controlNumber": 4498818,
"ItemNumber": "PS2W12077",
"shipment": {
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": 1638
}
},
{
"id": 936,
"controlNumber": 4498815,
"ItemNumber": "PS2T01096",
"shipment": {
"id": 11,
"Item": "PS2T01096",
"ColorCode": "MALDI",
"qty": 1212
}
},
]
controlNumber 4498818
has two shipment data with two qty
what I want is to show one controlNumber
with total qty
of 3276
what I have retired is return total qty
of all controlNumber
$result = $collection->pipe(function ($collection) {
return collect([
'shipment_qty' => $collection->sum('shipment.qty'),
]);
});
the output should be as follows
"collection": [
{
"id": 983,
"controlNumber": 4498818,
"ItemNumber": "PS2W12077",
"shipment": {
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": 3276
}
},
{
"id": 936,
"controlNumber": 4498815,
"ItemNumber": "PS2T01096",
"shipment": {
"id": 11,
"Item": "PS2T01096",
"ColorCode": "MALDI",
"qty": 1212
}
},
]
Upvotes: 0
Views: 898
Reputation: 1708
With this you get a collection where key is controlNumber
and value is sum of shipment->qty
.
$collection->mapToGroups(function ($item) {
return [$item->controlNumber => $item->shipment->qty];
})->map->sum();
Upvotes: 0