Laravel Carbon Group 按月
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41483365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Carbon Group by Month
提问by Dev.Wol
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;
I'm getting the following back
我要回以下内容
{"month":null}
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?
在我的数据库中,我有五篇新闻文章都是在 2017 年 5 月 1 日创建的,所以我只得到一个回复是对的,但我没有得到当月的数字?
回答by Alexey Mezenin
You can use groupBy()
method with closure:
您可以使用groupBy()
带闭包的方法:
$months = NewsItem::groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m');
})->get();
Or get data first and then use groupBy()
on the Eloquent collection:
或者先获取数据,然后groupBy()
在 Eloquent 集合上使用:
$months = NewsItem::get()->groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m');
});
回答by Robert
Why do you need the group by clause in your usecase?
为什么在用例中需要 group by 子句?
You are not fetching any additional data for which a group by is required, you just want to have a list of distinct months, so use distinct.
您不会获取需要 group by 的任何其他数据,您只想获得不同月份的列表,因此请使用 distinct。
$months = NewsItem::selectRaw("MONTH(created_at) as month")->distinct()->get();
Also looking at the solution provided by Alexey, you'll need to fetch the entire dataset from the DB, which is highly inefficient looking at what you are trying to do. A distinct()
query would be much faster than a select *
and group the results in PHP.
还要查看 Alexey 提供的解决方案,您需要从数据库中获取整个数据集,这在查看您要执行的操作时效率非常低。一个distinct()
查询会比更快select *
和组的结果PHP。
Edit:
编辑:
Little sidenote here, the reason you get null
returned as value is because you use a string in the MONTH()
function instead of the actual field.
这里有一点旁注,您null
作为值返回的原因是因为您在MONTH()
函数中使用了字符串而不是实际字段。
回答by Dayachand Patel
You can simply using groupby and mysql MONTH.
您可以简单地使用 groupby 和 mysql MONTH。
$months = NewsItem::groupby(\DB::raw('MONTH(created_at) as month'))->get();
回答by shamaseen
You can do it this way:
你可以这样做:
NewsItem::get(["*",\DB::raw('MONTH(created_at) as month')])->groupBy('month');