如何遍历数组并对属于相同 id 的值求和 Laravel

How to loop through an array and sum values that belong to the same id with Laravel

我是 php 、laravel 和 sql 的初学者(不到 2 周前开始),我不知道如何解决问题。 我有 2 tables:

现在从 table cf_invoice_claim_items 中获取这个数据样本,我需要使用 Laravel 做的是编写一个对 tot_qty 求和的作业来自 cf_invoice_claim_items 每个等于 so_invoice_item_id 并将结果值保存到相应 cf_so_invoice_items id 的 table cf_so_invoice_items 列 tot_claimed 中。 例如,从上面的屏幕截图中,您可以看到 invoice_claim_id 31 有两行 so_invoice_item_id 1 和两行 so_invoice_item_id 5。要写入的作业将写入 table cf_so_invoice_items id 1 为 4,id 5 为 22。

目前的代码如下:

class UpdateSoInvoiceItemsTotals implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $claim_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($claim_id)
    {
        $this->claim_id = $claim_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            // take all the claim items that belong to the claim id passed
            // CfInvoiceClaimItem is the model for the table cf_invoice_claim_items
            $claimItems = CfInvoiceClaimItem::select(['cf_invoice_claim_items.*'])
                ->where('cf_invoice_claim_items.invoice_claim_id', '=', $this->claim_id)
                ->get();

            // loop through the claim items and for each claim Item linked to the same  so_invoice_item_id sum the tot_qty and save it into the cf_so_invoice_items table with the corresponding id

            foreach($claimItems as $claimItem){
               foreach($claimItem->so_invoice_item_id as so_invoice_item_id) {
                 // code to write
               }
            }
        } catch(\Throwable $e) {
            // settare errore
            // $this->setError($claim->id, "ERR_GENERIC");
        }
    }
}

我被困在这里是因为我不知道如何遍历

claimItems->cf_so_invoice_items 并对具有相同 ID 的 cf_so_invoice_items 求和 tot_qty。

如comants所说,直接在query中求和数量,用thresult去udqate

请不要使用数据图片见Why should I not upload images of code/data/errors when asking a question?

    try {
        // take all the claim items that belong to the claim id passed
        // CfInvoiceClaimItem is the model for the table cf_invoice_claim_items
        $claimItems = CfInvoiceClaimItem::select(['cf_invoice_claim_items.*, DB::raw('SUM(tot_qty) AS sum_of_qty')'])
            ->where('cf_invoice_claim_items.invoice_claim_id', '=', $this->claim_id)
            ->get();

        // loop through the claim items and for each claim Item linked to the same  so_invoice_item_id sum the tot_qty and save it into the cf_so_invoice_items table with the corresponding id

        // You get only 1 result drom the select query as long as you don't use `GROUP BY`

        foreach($claimItems as $claimItem){
           $UpdateItems = cf_so_invoice_items::where('so_invoice_id', '=', $this->claim_id)
          ->update(['tot_claimed' => $claimItem->sum_of_qty]);
        }