Laravel using Sum and Groupby(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 使用 Sum 和 Groupby


- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01