本文介紹了Laravel Carbon Group 按月的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
誰(shuí)能看出我做錯(cuò)了什么?
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;
我要回以下內(nèi)容
{"month":null}
在我的數(shù)據(jù)庫(kù)中,我有五篇新聞文章都是在 2017 年 5 月 1 日創(chuàng)建的,所以我只收到一個(gè)回復(fù)??是對(duì)的,但我沒(méi)有得到當(dāng)月的數(shù)字?
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();
或者先獲取數(shù)據(jù),然后在 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');
});
這篇關(guān)于Laravel Carbon Group 按月的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!