如何在laravel中用groupBy查询求和列



我在数据库中有多条记录具有相同的产品名称。现在我希望所有的记录都应该来一次,但它们的数量栏应该是总和。我想按月和按年计算数量。

它将基本上显示每年和每月的产品摘要。

订单表迁移

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

这是一个伪查询,我不知道如何启动

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

尝试在集合上使用groupBy

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

顺便说一句,quantity列应该是数字类型,比如integer和unsigned。

对于任何需要容纳255个以上字符的列,请使用text/medialText/longText作为列数据类型。

Laravel文档:https://laravel.com/docs/8.x/migrations#available-列类型

最新更新