Laravel使用Sum和Groupby [英] Laravel using Sum and Groupby

查看:1822
本文介绍了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();
    });

推荐答案

该收集组不是由雄辩的groupby

that a collection group by not an eloquent groupby

如果您想雄辩地做到这一点,那就得

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆