laravel - Laravel 列求和
问题描述
我有这个查询
$installments = Installment::where('merchant_id',1)->with('bills')->get();
。
我需要获取表中存在sum()
的列。我在控制器中试过这个:bill_amount
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 中结合两个表来查看视图并进行求和,然后从视图中进行选择。
您在数据库中创建类似:(需要根据您的表进行调整)
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>)
推荐阅读
- c# - 在我的应用程序中禁用系统字体大小效果
- angularjs - 有没有办法在 dom 操作之后更新 Angular 绑定?
- jquery - 删除粘贴 jQuery 上的字符
- python - 在字典中查找与条件匹配的值
- java - java,没有连接到sql server
- monitoring - 使用来自不同模板的项目创建 Zabbix 触发器
- html - 如何将 mjpeg 播放为视频而不是图像?
- css - 具有两个类之一但不是两者的元素的选择器
- android - Android 应用程序在 Firebase 手机身份验证时崩溃
- codeigniter - 将 Mcrypt 库安装到谷歌云