[英]Getting timezone not found error while performing group by month in Laravel Carbon
[英]Laravel Carbon Group by Month
誰能看到我做錯了什么?
我試圖輸出所有月份,但將它們分組以便它們是唯一的。
$months = NewsItem::select(DB::raw('MONTH("created_at") as month'))->groupBy('month')->get();
return $months;
我要回以下內容
{"month":null}
在我的數據庫中,我有五篇新聞文章都是在 2017 年 5 月 1 日創建的,所以我只得到一個回復是對的,但我沒有得到當月的數字?
您可以將groupBy()
方法與閉包一起使用:
$months = NewsItem::groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m');
})->get();
或者先獲取數據,然后在groupBy()
集合上使用groupBy()
:
$months = NewsItem::get()->groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m');
});
為什么在用例中需要 group by 子句?
您不會獲取需要 group by 的任何其他數據,您只想獲得不同月份的列表,因此請使用 distinct。
$months = NewsItem::selectRaw("MONTH(created_at) as month")->distinct()->get();
同時查看 Alexey 提供的解決方案,您需要從數據庫中獲取整個數據集,這在查看您要執行的操作時效率非常低。 distinct()
查詢比select *
查詢快得多,並在 PHP 中對結果進行分組。
編輯:
這里有一點旁注,您將null
作為值返回的原因是因為您在MONTH()
函數中使用了字符串而不是實際字段。
您可以簡單地使用 groupby 和 mysql MONTH。
$months = NewsItem::groupby(\DB::raw('MONTH(created_at) as month'))->get();
你可以這樣做:
NewsItem::get(["*",\DB::raw('MONTH(created_at) as month')])->groupBy('month');
要按月獲得收入,您可以嘗試以下代碼:-
$getMonthlyReport = OrderMaster::select(DB::raw("sum(order_total_amt) as earnings,date_format(order_date, '%Y-%m') as YearMonth"))
->groupBy('order_date')
->get();
$month = NewsItem::select(
DB::raw('DATE_FORMAT(created_at, "%M") as month'))
->groupBy('month')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.