php - Laravel 使用 Sum 和 Groupby

标签 php laravel eloquent laravel-5.6 laravel-collection

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

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

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

相关文章:

php - 如何根据条件复制多维子数组值?

PHP OOP 插入数据

php - 将 RSS pubDate 转换为时间戳

php - Laravel Eloquent 检查日期是否与数据库中的日期不相等

php - Laravel 4 多对多从两个表中获取所有数据

php - 识别字符串是否为驼峰式

laravel - 如何在 cpanel 中运行 artisan 命令

laravel - 如何在获取路由中将默认参数传递给 Laravel Controller

php - 从 iframe 内部发布时的 Laravel TokenMismatchExpection

php - laravel 获取带有 where 子句的关系 hasMany 模型