Laravel Carbon Group 按月

2021-12-26 00:00:00 php mysql laravel laravel-5 eloquent

谁能看出我做错了什么?

Can anyone see what I'm doing wrong?

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

I'm trying to output all the months but group them so they are unique.

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

我要回以下内容

{"month":null}

在我的数据库中,我有五篇新闻文章都是在 2017 年 5 月 1 日创建的,所以我只收到一个回复​​是对的,但我没有得到当月的数字?

In my database I have five news articles all created_at 05/01/2017 so it's right that I only get one response but I'm not getting the number of the month back?

推荐答案

你可以使用带有闭包的 groupBy() 方法:

You can use groupBy() method with closure:

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

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

Or get data first and then use groupBy() on the Eloquent collection:

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

相关文章