Laravel Carbon Group按月 [英] Laravel Carbon Group by Month

查看:102
本文介绍了Laravel Carbon Group按月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以看到我在做什么错吗?

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按月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆