mardi 28 juillet 2020

Laravel: Combining transformed data based on common field

I am transforming some data from a query within my controller and returning it the frontend. I am getting an array of custom transformed "Orders" with the info I need. I will be calling this endpoint every few seconds. I am trying to see if there is a way I can combine the total of all the orders that have the same customer_id

Controller

 $orders = Order.where("type", "=", "valid")->get();

   foreach ($orders as $order) {
        $ordersArray[] = [
            'order_id' => $order->id,
            'customer_name' => $order->customer_id),
            'customer_id' => $order->customer_id,
            'total' => $order->total,
        ];
    }

    return [
        'paidOrders'    =>  $ordersArray,
    ];

example of what is returned to the frontend

[
   {order_id: 314, customer_name: "Martin", customer_id: 71, total: 66},
   {order_id: 315, customer_name: "Barry", customer_id: 82, total: 217},
   {order_id: 316, customer_name: "Barry", customer_id: 82, total: 217},
   {order_id: 317, customer_name: "Barry", customer_id: 82, total: 147},
]

example of what I'd like returned -- just combine the total for the same customer

[
   {order_id: 314, customer_name: "Martin", customer_id: 71, total: 66},
   {order_id: ?, customer_name: "Barry", customer_id: 82, total: 581},
]


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2EtpML4
via IFTTT

Aucun commentaire:

Enregistrer un commentaire