Home  >  Q&A  >  body text

How to calculate the sum of two columns and the number of related relationships in laravel?

I have two tables: buyers and orders. Buyers have many orders.

I want the sum of all buyers and the number of orders and two columns of orders (price, fee) within a specific time period. I can get the count by doing the following,

Buyer::withCount([
    'orders' => fn ($query) => $query
        ->where('created_at', '>=', $dateTo)
])
->get();

But how to get the sum of a specified time period (->where('created_at', '>=', $dateTo))?

P粉788571316P粉788571316264 days ago483

reply all(2)I'll reply

  • P粉567112391

    P粉5671123912024-02-22 09:50:28

    In the same way you have withSum(), here is how you can do it

    Buyer::withCount([
                'orders' => fn($query) => $query->where('created_at', '>=', $dateTo),
            ])->withSum([
                'orders' => fn($query) => $query->where('created_at', '>=', $dateTo),
            ], 'price')->withSum([
                'orders' => fn($query) => $query->where('created_at', '>=', $dateTo),
            ], 'charge')->get();

    reply
    0
  • P粉189606269

    P粉1896062692024-02-22 00:03:31

    To use a variable inside a closure, you need to use use() to send its value to the function.

    For using withSum({relation},{column}) you need to call it separately for each one.

    Buyer::withCount([
            'orders' => function ($query) use ($dateTo) { 
                $query->where('created_at', '>=', $dateTo);
            }
        ])
        ->withSum([
            'orders' => function ($query) use ($dateTo) { 
                $query->where('created_at', '>=', $dateTo);
            }
        ], 'price')
        ->withSum([
            'orders' => function ($query) use ($dateTo) { 
                $query->where('created_at', '>=', $dateTo);
            }
        ], 'charge')
        ->get();

    withSum() Only available in Laravel version 8 or higher.

    EditArrow function syntax

    Buyer::withCount([
            'orders' => fn ($query) $query->where('created_at', '>=', $dateTo),
        ])
        ->withSum(['orders' => fn ($query) $query->where('created_at', '>=', $dateTo)], 'price')
        ->withSum(['orders' => fn ($query) $query->where('created_at', '>=', $dateTo)], 'charge')
        ->get();

    reply
    0
  • Cancelreply