简体   繁体   中英

How to sum column with groupBy query in laravel?

I have multiple record in database with same product name. Now I want that all the record should come once but their quantity column should be sum up. I want to sum quantity on monthly and yearly basis.

It will basically display summary of product on yearly and monthly basis.

Order Table migration

 public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('amzid',500)->nullable();
            $table->string('samid',500)->nullable();
            $table->string('quantity',500)->nullable();
            $table->string('samq',500)->nullable();
            $table->text('samp',5000)->nullable();
            $table->text('same')->nullable();
            $table->string('pname',7000)->nullable();
            $table->text('note')->nullable();
            $table->timestamps();
        });
    }

This is dummy query i dont know how to start

Order::groupBy('pname')->sum('quantity')->lastthirtyDay() ??

Try to use groupBy on collections

$last30Days = Instock::whereDate('created_at', '>', now()->subMonth())->get()
    ->groupBy('pname')
    ->mapWithKeys(function($item, $pname){
        return [$pname => $item->sum('quantity')];
    });

$lastOneYear = Instock::whereDate('created_at', '>', now()->subYear())->get()
    ->groupBy('pname')
    ->mapWithKeys(function($item, $pname){
        return [$pname => $item->sum('quantity')];
    });

By the way quantity column should be numeric type like integer and unsigned.

And for any column which needs to hold more than 255 characters, use text/mediumText/longText as column datatype.

Laravel docs: https://laravel.com/docs/8.x/migrations#available-column-types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM