Laravel Carbon Group by Month(Laravel Carbon Group 按月)
本文介绍了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 按月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Laravel Carbon Group 按月


基础教程推荐
猜你喜欢
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- php中的PDF导出 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的foreach复选框POST 2021-01-01