Laravel Carbon Group按月

Dev*_*Wol 5 php mysql laravel eloquent laravel-5

谁能看到我在做什么错?

我试图输出所有月份,但将它们分组以便它们是唯一的。

$months = NewsItem::select(DB::raw('MONTH("created_at") as month'))->groupBy('month')->get();
return $months;
Run Code Online (Sandbox Code Playgroud)

我回来了以下内容

{"month":null}
Run Code Online (Sandbox Code Playgroud)

在我的数据库中,我有五篇新闻文章全部创建于2017年5月1日,因此,我只收到一个答复,但是我没有得到当月的数字,这是对的。

Ale*_*nin 11

您可以将groupBy()方法与闭包一起使用:

 $months = NewsItem::groupBy(function($d) {
     return Carbon::parse($d->created_at)->format('m');
 })->get();
Run Code Online (Sandbox Code Playgroud)

或者先获取数据,然后groupBy()在Eloquent集合上使用:

 $months = NewsItem::get()->groupBy(function($d) {
     return Carbon::parse($d->created_at)->format('m');
 });
Run Code Online (Sandbox Code Playgroud)

  • 嗨,这给了我strtolower()期望参数1为字符串,给定对象错误。 (4认同)