我想获取每个月的数量总和,以便我可以在条形图上显示每月的数量
这是我的想法,但没有锻炼
$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();
});
最佳答案
集合组不是 Eloquent 组
如果你想用 Eloquent 方式做到这一点,必须:
$data1 = Borrow::selectRaw('SUM(quantity) as qt, MONTH(created_at) as borrowMonth')
->groupBy('borrowMonth')->get();
如果你想用集合的groupBy方法来实现,你应该先做get,然后再做groupBy。
就像,虽然我不确定你想通过回调中所做的事情来完成什么......
$data1 = Borrow::get()->groupBy(function($d) {
return Carbon::parse($d->created_at)->format('m')->sum('quantity');
});
关于php - Laravel 使用 Sum 和 Groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58256968/