简体   繁体   中英

Sum of sub query result with group by laravel eloquent

I have two tables one transactions and another transaction_charges each transaction might have multiple transaction charges means an has many relationships. now what I need is to get transactions that occured in a month/year/week. it would be better if I can do a group by inside the query itself rather than doing a loop with the model collections.

so far I have written code to fetch the transactions with its total charge

 $defaults = collect([]);
    /** @var Builder $transactions */
    $transactions = app(TransactionServices::class)
        ->getTransactions($defaults->merge($options))
        ->has('charges')->has('operation')->selectSub(function ($query){
            /** @var Builder $query */
            $query->selectRaw('SUM(amount)')->from('transaction_charges tc')
                ->whereRaw('tc.transaction_id = transaction.transaction_id');
        }, 'totalCharge');

but to get the monthly result I need to do a group by but I don't think the group by will fetch correct aggregated result from the subquery as here what I need is the sum of the totalCharge in a month/week/group. so how I can get the transactions with its charges sum up to the monthly/Yearly group

I don't know well how your system works but I did an intent of understand it and think one possible solution for your problem.
I made my best effort to explain the code. I Hope you understand that english is not my native language.

// I suppose that TransactionServices represents "transaction" Table and has transaction_charges
$transactions = TransactionServices::has('charges')->get(); // If I understand well your code that returns the transactions that has charges.
// $transactions = TransactionServices::has('charges')->has('operation')->get(); // that returns the transactions that has charges AND operation.

// the month to filter the charges
$month = 'march'; // selected month can be dynamic this is an example

// Get all TransactionServices with total amount of charges
$transactionsWithTotalCharge = $transactions->each(function ($transaction, $key) {
    $totalAmount = $transaction->charges->where('month', $month)->sum('amount'); // This make the sum of all charges of march for that transaction 
    $transaction->put('chargesTotalAmount' , $totalAmount); // This add chargesTotalAmount to every TransactionServices
    return $transaction;
});

// You can verify if the sum is correct
foreach($transactionsWithTotalCharge as $transaction) {
    // dd($transaction); 
    dd($transaction->chargesTotalAmount); 
}

I could not test that and hope that work

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