gpt4 book ai didi

php - Laravel 使用 Sum 和 Groupby

转载 作者:行者123 更新时间:2023-11-29 15:35:44 24 4
gpt4 key购买 nike

我想获取每个月的数量总和,以便我可以在条形图上显示每月的数量

这是我的想法,但没有锻炼

 $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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com