laravel eloquent的分组查询结果总和

时间:2018-03-12 19:30:39

标签: php mysql laravel

我有两个表transactions而另一个transaction_charges每个事务可能有多个交易费用意味着有很多关系。现在我需要的是获得一个月/一年/一周内发生的交易。如果我可以在查询本身内部执行group by而不是使用模型集合进行循环,那会更好。

到目前为止,我已编写代码来获取带有总费用的交易

 $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');

但要获得每月结果,我需要分组,但我不认为分组将从子查询中获取正确的聚合结果,因为我需要的是totalCharge的总和在一个月/周/组。所以我如何能够将其收费与每月/每年的小组进行交易

1 个答案:

答案 0 :(得分:0)

我不太了解您的系统是如何工作的,但我的目的是了解它并为您的问题考虑一种可能的解决方案。
我尽最大努力解释代码。我希望你明白英语不是我的母语。

// 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); 
}

我无法测试并希望工作

相关问题