【问题标题】:Laravel group by weekday and get total countLaravel 按工作日分组并获取总数
【发布时间】:2021-12-29 13:23:55
【问题描述】:

要获取工作日的订单总数,我使用:

Order::select('*')
  ->get()
  ->groupBy(function($date) {
    return Carbon::parse($date->created_at)->format('l');
  });

我想补充的是,它会在每个工作日返回已订购商品的数量,这是 Order 模型上名为 item_count 的属性。我尝试在查询中使用sum(),但这不起作用。

【问题讨论】:

  • 这能回答你的问题吗? Laravel Eloquent: sum with groupBy
  • 不,这给了Call to a member function groupBy() on string。也许是因为在我的情况下 groupBy 是一个函数?

标签: laravel


【解决方案1】:

这是解决方案:

Order::select(
    DB::raw('DAYNAME(created_at) AS week_day'),
    DB::raw('WEEKDAY(created_at) as day'),
    DB::raw("SUM(item_count) as items_total")
  )
  ->orderBy('day')
  ->groupBy(DB::raw('DAYNAME(created_at)'))
  ->get();

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2021-01-12
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    相关资源
    最近更新 更多