简体   繁体   中英

How to get the sum column values in laravel in model?

I was told that I can get the sum of certain column values using a function in model instead of doing this code with foreach :

$orders = Order::where('place_id',1)->select('delivery_fees')->get()->toArray();
        $orderArray = [];
        foreach ($orders as $order)
        {
            $orderArray[] = $order['delivery_fees'];
        }
$deliveryCostTotal = array_sum($orderArray);

How can I do that ?

使用 Mysql SUM

$deliveryCostTotal = Order::where('place_id',1)->selectRaw('SUM(delivery_fees) AS cost_total')->value('cost_total');

You can use laravel sum function

$deliveryCostTotal = Order::where('place_id',1)->sum('delivery_fees');

https://laravel.com/docs/6.x/queries#aggregates

请尝试这样

$deliveryFees = Order::where('place_id',1)->sum('delivery_fees');

As your problem is solved but I am considering my answer as clearing your confusion in array_sum and adding data in array . because you are only setting value to array and overriding it, use array_push to add data in array.

 $orders = Order::where('place_id',1)->select('delivery_fees')->get()->toArray();
            $orderArray = [];
            foreach ($orders as $order)
            {
               array_push($orderArray,$order['delivery_fees']);
            }
    $deliveryCostTotal = array_sum($orderArray);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM