Laravel using Sum and Groupby

♀尐吖头ヾ 提交于 2019-12-31 03:01:42

问题


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();

My table structure

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();
    });

回答1:


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();

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');
 });



回答2:


try this query , you will get month wise count :

use DB;


 $month_wise_count=DB::table("borrows")
        ->select(DB::raw('CONCAT(MONTHNAME(created_at), "-",  YEAR(created_at)) AS month_year'),
                DB::raw("MONTH(created_at) as month , YEAR(created_at) as year"),
                DB::raw("(COUNT(*)) as total_records"),
                DB::row("(SUM('quantity') as total_value"))
        ->orderBy(DB::raw("MONTH(created_at),YEAR(created_at)"))
        ->groupBy(DB::raw("MONTH(created_at),YEAR(created_at)"))
        ->get();


来源:https://stackoverflow.com/questions/52041367/laravel-using-sum-and-groupby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!