【问题标题】:Why does aggregation function does not work in my laravel SQL Query?为什么聚合函数在我的 laravel SQL 查询中不起作用?
【发布时间】:2018-11-14 06:31:02
【问题描述】:
$year = date("y"); 
for($i=1;$i<=12;$i++) 
{ 
   $MonthlyReceive = DB::table('order_items') ->whereBetween('created_at',array($year.'-'.$i.'-1',$year.'-'.$i.'-31')) ->select(DB::raw('sum(price*quantity)'))->where('quantity','<','0');
   return $MonthlyReceive; 
}

// table name "order_items"
// id |product_id |quantity |price |order_id

【问题讨论】:

  • 我想要每个月的总收款金额,所以请在这个for循环中给我一个解决方案。
  • 您收到什么错误或意外行为?
  • 收货:[[{sum(pricequantity): null}], [{sum(pricequantity): null}], [{sum(price数量): null}],…] 0: [{sum(pricequantity): null}] 0: {sum(pricequantity): null} 1: [{sum(pricequantity): null}] 2: [{sum(pricequantity): null}] 3: [{sum(pricequantity): null}] 4: [{sum(price数量): null}] 5: [{sum(pricequantity): null}] 6: [{sum(pricequantity): null}] 7: [{sum(price数量): null}] 8: [{sum(pricequantity): null}] 9: [{sum(pricequantity): null}] 10: [{sum(pricequantity) ): -16800}] 11: [{sum(pricequantity): null}]
  • 它在数组 11 值上的工作还可以,但没有显示在我的仪表板图中
  • @sr_atiq 如果可能,请添加您的错误并附上一些解释,这样更好理解。

标签: php mysql eloquent laravel-5.2


【解决方案1】:

您可以在没有循环的情况下按月获取汇总数据。

   $MonthlyReceive = DB::table('order_items')
                ->select(DB::raw('sum(price*quantity) as amnt'))
                ->whereRaw('date(created_at) between "'.$year.'-01-01" and "'.$year.'-12-31"')
                ->where('quantity','<','0')
                ->groupBy(DB::raw("date_format(created_at, '%Y-%M')"));

只需将group by 与聚合函数一起使用即可。

【讨论】:

  • 还没有工作。并且需要循环你的甲酸盐只给我看一月份的值
【解决方案2】:
$year = date("y");
for($i=1; $i<=12; $i++) {
    $MonthlyReceive = DB::table('order_items')
        ->whereBetween('created_at', array($year.'-'.$i.'-1',$year.'-'.$i.'-31'))
        ->where('quantity', '>', '0')
        ->sum(DB::raw('price*quantity'));
    return $MonthlyReceive;
}

我已使用此代码修复它。

【讨论】:

  • 太棒了!但尽量避免循环。我也是这样工作的,没有循环。
  • @er.irfankhan11 好的,我会尽量避免循环。感谢您的回复。
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2020-03-10
  • 2016-04-14
相关资源
最近更新 更多