ids = $ids; } public function handle() { if (empty($this->ids)) { return; } try { $mainIds = $this->ids; $affectedDeviceIds = DB::table('monthly_dd_order_details') ->whereIn('main_id', $mainIds) ->where('del_time', 0) ->pluck('device_id') ->unique() // 去重 ->toArray(); if (empty($affectedDeviceIds)) return; // 3. 【核心改变】:脱离单号限制!直接去查这些设备在全表里“所有的”历史折旧总和 $globalDepreciationMap = DB::table('monthly_dd_order_details') ->select('device_id', DB::raw('SUM(depreciation_amount) as total_amount')) ->whereIn('device_id', $affectedDeviceIds) ->where('del_time', 0) ->groupBy('device_id') ->pluck('total_amount', 'device_id') // 生成 [设备ID => 历史所有折旧累计总额] ->toArray(); // 4. 分批更新到设备表中 $chunkSize = 100; $chunks = array_chunk($affectedDeviceIds, $chunkSize); foreach ($chunks as $chunkDeviceIds) { DB::transaction(function () use ($chunkDeviceIds, $globalDepreciationMap) { foreach ($chunkDeviceIds as $deviceId) { // 拿到该设备有史以来所有的折旧总和(如果没有查到说明被删光了,默认为 0) $totalAmount = (float)($globalDepreciationMap[$deviceId] ?? 0); DB::table('device') ->where('id', $deviceId) ->update([ 'total_depreciation' => $totalAmount, // 绝对总额直接覆盖 ]); } }); } } catch (\Throwable $e) { $this->delete(); } } }