Laravel:按月份和输出月份名称分组用户

时间:2018-03-17 14:13:10

标签: laravel laravel-5

我按月查询在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}]

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

很难说没有看到你的数据库结构,但这样的事情会好的。如上所述,您显示的输出不与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,
                      ];
                    });
                });

答案 2 :(得分:0)

$statement = Purchase::selectRaw('monthname(purchase_date) month')
            ->groupBy('month')
            ->orderByRaw('min(purchase_date) asc')
        ->get();
        echo "<pre>";
        print_r($statement);
        die;

答案 3 :(得分:0)

只需使用此

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