您好我正在尝试按月分组记录和订单总和价格
我试过这样的事情
$order = Order::select(DB::raw('sum(price) as sums'))->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y-m');
});
但没有运气, 我想获得我以后可以在数据表中实现的集合吗?
答案 0 :(得分:5)
请试试这个:
$orders = Order::select(
DB::raw('sum(price) as sums'),
DB::raw("DATE_FORMAT(created_at,'%M %Y') as months")
)
->groupBy('months')
->get();
答案 1 :(得分:0)
作为 @Anowar Hossain 答案的补充,您可以使用此解决方案进一步获取其他月份的索引,而不管它们中是否有值。
$orders = Order::select(
DB::raw('sum(price) as sums'),
DB::raw("DATE_FORMAT(created_at,'%M %Y') as months"),
DB::raw("DATE_FORMAT(created_at,'%m') as monthKey")
)
->groupBy('months', 'monthKey')
->orderBy('created_at', 'ASC')
->get();
如果您只想提供当年的数据,则可以考虑这样做:
$orders = Order::select(
DB::raw('sum(price) as sums'),
DB::raw("DATE_FORMAT(created_at,'%m') as monthKey")
)
->whereYear('created_at', date('Y'))
->groupBy('monthKey')
->orderBy('created_at', 'ASC')
->get();
然后创建一个包含12个零值的数组,如下所示:
$data = [0,0,0,0,0,0,0,0,0,0,0,0];
foreach($orders as $order){
$data[$order->monthKey-1] = $order->sums;
}
return $data; // [0,10000,5000,7000,9000,0,0,0,0,15000,0,0]
希望这可以帮助某个人!