谁能看出我做错了什么?
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');
});
这篇关于Laravel Carbon Group 按月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!