How to calculate the sum of two columns and the number of related relationships in laravel?
P粉788571316
P粉788571316 2024-02-21 11:59:52
0
2
475

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粉788571316
P粉788571316

reply all(2)
P粉567112391

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();
P粉189606269

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();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!