laravel - Laravel:使用另一个表中的变量在循环内求和
问题描述
我正在为一个小型 POS 项目制作销售报告图表,但我陷入了需要对 sales_item 表中的每个类别求和的部分。(我认为 grouBy() 函数将不起作用,因为有时某些类别尚未在 sales_item 表中,我需要为尚未在表中的类别获取 0。
我想要做的是通过执行以下操作对 sales_table 中的每个类别求和: 1st:获取类别表中的类别名称。2nd:使用带有循环的类别名称分别对sales_item进行求和。第三:返回类别数组及其总和。
这是我卡住的代码:编辑:用这个解决了它:
public function getCategorChartValue(){
$tst="";
$categories = Category::get();
$countCat = $categories->count();
for($i = 0;$i<=$countCat-1;$i++){
$cat = Category::get();
$sums = DB::table('sales')->where('category',$cat[$i]->id)->sum('total');
$tst .= $sums .',';
}
return $tst;
}
解决方案
类别::类
public function sales()
{
return $this->hasMany(Sales::class);
}
销售::类
public function category()
{
return $this->belongsTo(Category::class); // category_id in the sales table
}
在您的控制器中,您可以简单地使用withCount()
$categories = Category::select('id', 'name')->withCount('sales')->get()->toArray();
[
0 => [
"id" => 1,
"name" => "Books",
"sales_count" => 12
],
.
.
]
推荐阅读
- c# - 如果我有数千行,如何快速填充 asp listview
- php - socket_sendto():无法写入套接字 [1]:使用 papertrail 日志记录时不允许操作
- string - 如何在颤动的文本小部件中动态更改段落中某些单词的颜色
- javascript - 增加或减少输入值
- ionic4 - 无法安装 esc-pos-encoder-ionic
- java - Spring Boot 测试:如何使用 AOP 部分模拟服务
- java - Java - 将方法调用传递给方法
- android - 如何在 Android Studio 中使用 Kotlin 和 React Native?
- html - 如何保持两个div彼此相邻?
- tomcat - 访问 Tomcat 外部图像的网络磁盘上下文问题