【问题标题】:Get only unique item from collection and sum other values to one item仅从集合中获取唯一项目并将其他值相加到一项
【发布时间】:2018-05-15 13:19:30
【问题描述】:

我确实有这个 laravel 集合

    Collection {#239 ▼
      #items: array:2 [▼
        0 => array:21 [▼
          "dueDate" => "2017-09-29"
          "groupByCode" => "REMINDER"
          "date" => "2017-09-29"
          "number" => "9030014"
          "status" => "Reminder"
          "currencyCode" => "kr"
          "amount" => 1745.0
          "remainingAmount" => 1745.0

        ],
  2 => array:21 [▼
          "dueDate" => "2017-09-29"
          "groupByCode" => "REMINDER"
          "date" => "2017-09-29"
          "number" => "9030014"
          "status" => "Reminder"
          "currencyCode" => "kr"
          "amount" => 1345.0
          "remainingAmount" => 1745.0

        ],
        3 => array:21 [▼
          "dueDate" => "2017-09-29"
          "groupByCode" => "INVOICE"
          "date" => "2017-09-29"
          "number" => "9030026"
          "status" => "invoice"
          "currencyCode" => "kr"
          "amount" => 2389.0
          "remainingAmount" => 2389.0

        ]
      ]
    }

现在我的问题是如何根据状态仅获取唯一项目,例如上面的示例我有两个具有状态提醒的项目,而不是我想保持相同的集合格式,但作为回报只有一个状态为“提醒”的项目所有现有的键和总和将是两个提醒的总和....

我尝试使用 `where('status', ''Reminder')->first() 但不起作用,因为它只需要第一个元素。

所以输出应该是这样的:

    Collection {#239 ▼
      #items: array:2 [▼
        0 => array:21 [▼
          "dueDate" => "2017-09-29"
          "groupByCode" => "REMINDER"
          "date" => "2017-09-29"
          "number" => "9030014"
          "status" => "Reminder"
          "currencyCode" => "kr"
          "amount" => TOTAL OF BOTH REMINDERS
          "remainingAmount" => 1745.0

        ],
  2 => array:21 [▼
          "dueDate" => "2017-09-29"
          "groupByCode" => "INVOICE"
          "date" => "2017-09-29"
          "number" => "9030014"
          "status" => "Invoice"
          "currencyCode" => "kr"
          "amount" => 2312 
          "remainingAmount" => 1745.0

            ],
}

谢谢!

代码如下:

$invoices = $this->boatService->getInvoices(cleanSsn(session('ssn')));

$invoices = collect($invoices)->whereIn('status', ['Reminder', 'Invoice']); 

【问题讨论】:

  • 也分享你的尝试?
  • @user2486 ok 再次检查

标签: php laravel collections


【解决方案1】:

您可以进行原始查询来汇总项目并按状态对它们进行分组。试试这个:

$collection = \DB::table('invoices')
                 ->select(\DB::raw('sum(amount) as amount_total, status'))
                 ->groupBy('status')
                 ->get();

【讨论】:

  • 我只是想到了groupBy('groupByCode')groupBy('status')
  • 这是来自 api 服务
  • 只是一点点修正,可能他需要和而不是计数
猜你喜欢
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 2012-11-09
  • 2019-07-12
  • 1970-01-01
  • 2016-11-04
相关资源
最近更新 更多