【问题标题】:How to sum column with groupBy query in laravel?如何在 laravel 中对 groupBy 查询求和列?
【发布时间】:2021-03-27 07:02:33
【问题描述】:

我在数据库中有多个具有相同产品名称的记录。现在我希望所有记录都应该出现一次,但它们的数量列应该被总结。我想按月和按年汇总数量。

基本上会按年和月显示产品的汇总。

订单表迁移

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

【问题讨论】:

  • 你能编辑帖子并添加你的数据库结构吗
  • 好的,我正在编辑
  • 我编辑了我想分组的帖子添加表迁移按数量但按年和按月进行分组

标签: php database laravel laravel-5 eloquent


【解决方案1】:

尝试在集合上使用 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')];
    });

顺便说一下数量列应该是数字类型,比如整数和无符号。

对于任何需要包含超过 255 个字符的列,使用 text/mediumText/longText 作为列数据类型。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2021-11-13
    • 2015-08-29
    • 2018-11-17
    • 1970-01-01
    • 2021-05-14
    • 2015-12-03
    相关资源
    最近更新 更多