Laravel 使用 Sum 和 Groupby

Laravel using Sum and Groupby

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

这是我想的但没有锻炼

 $data1 = Borrow::groupBy(function($d) {
 return Carbon::parse($d->created_at)->format('m')->sum('quantity');
 })->get();

我的table结构

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

试试这个查询,你会得到每月的计数:

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