【发布时间】:2018-05-16 22:38:22
【问题描述】:
我有一个函数可以返回每天的销售额。这种方法的问题是我希望数据按日期存储,但我按以下顺序获取它们:
01-Dec
02-Dec
03-Dec
03-Nov
04-Nov
05-Nov
etc.
我明白为什么会发生这种情况,但我不知道如何解决它。我可以用 startofmonth 替换 subMonth(1) ,这将部分解决我的问题,但这不是我想要的。相反,我想退回最近 30 天的订单。
return DB::table('sales')
->select(\DB::RAW('DATE_FORMAT(created_at, "%d-%M") as date'), \DB::raw('COUNT(*) as count'))
->where('created_at', '>=', Carbon::now()->subMonth(1))
->orderBy('date')
->groupBy('date')
->get(['date', 'count'])
->keyBy('date')
->transform(function ($data) {
return $data->count;
});
我也试过 orderBy('created_at') 但它给了我下面的错误,我想避免更改 sql 模式。
Syntax error or access violation: 1055 Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'x.sales.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
编辑: 根据要求,这是return语句的sql查询
select DATE_FORMAT(created_at, "%d-%M") as date, COUNT(*) as count from `sales` where `created_at` >= ? group by `date` order by `date` asc
【问题讨论】:
-
请发布生成的 SQL
-
@lad2025 我刚刚做了:)
-
请尝试:
->groupBy('1')而不是->groupBy('date') -
为什么需要 groupBy ?
-
@George 我的建议有帮助吗?
标签: php mysql sql laravel laravel-5