Laravel 拉维列求和

Laravel 拉维列求和,laravel,eloquent,sum,relationship,Laravel,Eloquent,Sum,Relationship,我有这个问题 $installants=installation::where('merchant_id',1)->with('bills')->get() 我需要得到bill\u amount列的sum(),该列存在于bills表中。 我在控制器中尝试过此功能: $paid_amount = 0; $not_paid_amount = 0 ; foreach ($installments as $installment) { $paid_amount += $installm

我有这个问题
$installants=installation::where('merchant_id',1)->with('bills')->get()

我需要得到
bill\u amount
列的
sum()
,该列存在于
bills
表中。 我在控制器中尝试过此功能:

$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');
    }
这是一项工作,但我认为这不是最佳实践,
最好的方法是什么?

提前感谢

我认为您最好在DB中创建一个视图,将两个表组合在一起,进行求和,然后从视图中进行选择

在DB中创建如下内容:(需要根据ur表进行调整)

创建或替换视图'merchant\u bills'作为选择金额('bill`.'bill\u amount`),将'mr`.'merchant\u id`作为'merchant\u id``
from(`merchant``mr`,`bills``bill`)连接`farms``f`),其中(()和()
分组(由)

请解释一下,好吗?然后在DB中创建视图后,在Laravel中创建一个模型对象,并按照从表中选择的方式从中进行选择
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>)