本文介紹了Laravel 使用 Sum 和 Groupby的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想獲取每個月的數量總和,以便我可以在條形圖上顯示每月的數量
I would like to fetch sum of quantity in each month, so that I can display on bar chart quantities against month
這就是我想的,但沒有鍛煉
This is what I thought but didn't workout
$data1 = Borrow::groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m')->sum('quantity');
})->get();
我的表結構
Schema::create('borrows', function (Blueprint $table) {
$table->increments('id');
$table->integer('member_id');
$table->integer('book_id');
$table->integer('quantity');
$table->integer('status')->default(0);
$table->timestamps();
});
推薦答案
that a collection group by not an eloquent groupby
that a collection group by not an eloquent groupby
如果你想用 eloquent 來做,必須:
if you want to do it with eloquent, gotta:
$data1 = Borrow::selectRaw('SUM(quantity) as qt, MONTH(created_at) as borrowMonth')
->groupBy('borrowMonth')->get();
如果你想用集合 groupBy 方法來做,你應該先做 get,然后是 groupBy.
if you want to do it with the collection groupBy method, you should first do the get, then the groupBy.
就像,雖然我不確定你在回調中所做的事情要完成什么..
As in, though im not sure what you're trying to accomplish with what you do inside the callback..
$data1 = Borrow::get()->groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m')->sum('quantity');
});
這篇關于Laravel 使用 Sum 和 Groupby的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!