php - 为什么聚合函数在我的 laravel SQL 查询中不起作用?

标签 php mysql eloquent laravel-5

$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

最佳答案

您无需循环即可按月明智地获取汇总数据。

   $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即可。

关于php - 为什么聚合函数在我的 laravel SQL 查询中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53294318/

相关文章:

php - 如何为具有多对多关系的业务目录建立mySQL表结构?

php - 如何使用 CURRENT_TIMESTAMP 在 mysql 中将 Gregorian 格式转换为 Solar 格式

php - 如何在 Laravel Eloquent Collection 的each方法中使用break或continue?

php - 你如何验证一个属性是否可以在 php 中访问?

php - 在 PHP 中使用 Imagick 调整 .eps 大小并另存为 .jpg

mysql 在表名中使用变量

MySQL : replace occurence of a string in field except first one

mysql - 对于这个错误信息有什么解决办法吗?

php - MySQL - 通过引用同一表的外键对记录进行排序/分组(Laravel,ORM)

php - 扩展/覆盖 Eloquent 创建方法 - 不能使静态方法非静态