【问题标题】:Laravel : Group users by month and output month nameLaravel:按月份分组用户并输出月份名称
【发布时间】:2018-08-26 12:45:40
【问题描述】:

我正在按月查询在 Laravel 中创建的用户,这是我的代码

  $devlist = DB::table("users")
                ->select("id" ,DB::raw("(COUNT(*)) as month"))
                ->orderBy('created_at')
                ->groupBy(DB::raw("MONTH(created_at)"))
                ->get();

这是给我的

[{"id":1,"month":3},{"id":4,"month":4}]

我怎样才能输出月份而不是仅仅输出月份?所以我的预期结果是

[{"id":1,"january":3},{"id":4,"febuary":4}]

【问题讨论】:

  • 月份标签是否实际存储在数据库中?
  • 否,但 created_at 字段是包含月份的时间戳
  • 当前结果没有意义——如果它的“groupBy”你会期望有一个嵌套的结果?它目前看起来很平坦。我希望看到类似[{ "may": [{ "id":1, "month": 3 }, { "id":2, "month": 4 }] }]
  • 我不得不说,你的另一个问题被人们很好地回答了。你怎么又问这个问题了?另外,我不建议这样设置,因为那样数据不是很有用。也许应该是:[{"id":1,"month":"january"},{"id":4,"month":"febuary"}]
  • 我的另一个问题得到了完美的回答,但是,这是一个关于输出月份名称的不同问题

标签: laravel laravel-5


【解决方案1】:

不看数据库很难回答这个问题,但我希望这会有所帮助:

$devlist = DB::table("users")
   ->select(DB::raw('EXTRACT(MONTH FROM created_at) AS month, COUNT(id) as id'))
   ->orderBy('created_at')
   ->groupBy(DB::raw('month'))
   ->get();

【讨论】:

    【解决方案2】:
    $statement = Purchase::selectRaw('monthname(purchase_date) month')
                ->groupBy('month')
                ->orderByRaw('min(purchase_date) asc')
            ->get();
            echo "<pre>";
            print_r($statement);
            die;
    

    【讨论】:

      【解决方案3】:

      如果不查看您的数据库结构,很难判断,但这样就可以了。如前所述,您显示的输出与 groupBy 子句不相符,但假设 groupBy 是正确的,这将按照您需要的方式进行重组:

      $devlist = DB::table("users")
                      ->select("id" ,DB::raw("(COUNT(*)) as month"))
                      ->orderBy('created_at')
                      ->groupBy(DB::raw("MONTH(created_at)"))
                      ->get()
                      ->map(function($monthItems, $month) {
                          return $monthItems->map(function($item) use ($month) {
                            return [
                                'id' => $item->id,
                                $month => $item->month,
                            ];
                          });
                      });
      

      【讨论】:

        【解决方案4】:

        只需使用这个

        \App\Model::selectRaw('monthname(date) as month, sum(total_amount) as total_sale')
                ->groupBy('month')
                ->orderByRaw('min(date) desc')
                ->get();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-19
          • 1970-01-01
          相关资源
          最近更新 更多