首页 > 解决方案 > 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;

}

标签: laravel

解决方案


类别::类

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
  ],
  .
  .
]

推荐阅读