【问题标题】:Laravel: Sum inside loop using variables from another tableLaravel:使用另一个表中的变量在循环内求和
【发布时间】:2020-05-24 22:12:36
【问题描述】:

我正在为一个小型 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;

}

【问题讨论】:

  • 提示:以 SQL 查询的形式编写该“算法”,然后您会更容易理解如何创建执行您想要的 Eloquent 查询(也为我们了解你真正想要什么)

标签: laravel


【解决方案1】:

类别::类

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多