首页 > 解决方案 > Laravel 列求和

问题描述

我有这个查询
$installments = Installment::where('merchant_id',1)->with('bills')->get();

我需要获取表中存在sum()的列。我在控制器中试过这个:bill_amountbills

$paid_amount = 0;
$not_paid_amount = 0 ;
 foreach ($installments as $installment) {
        $paid_amount += $installment->bills->where('status',1)->sum('bill_amount');
        $not_paid_amount += $installment->bills->where('status',0)->sum('bill_amount');
    }

这项工作,但我认为这不是最佳实践,
最好的方法是什么?
提前致谢

标签: laraveleloquentsumrelationship

解决方案


我认为您可以更好地在 DB 中结合两个表来查看视图并进行求和,然后从视图中进行选择。

您在数据库中创建类似:(需要根据您的表进行调整)

CREATE or replace VIEW `merchatnt_bills` AS select sum(`bill`.`bill_amount`),`mr`.`merchant_id` AS `merchant_id`
 from ((`merchant` `mr`, `bills` `bill`) join `farms` `f`) where ((<put one to many relatuion between two tables>) and (<any other condition u like>)
group by <columns>)

推荐阅读