setDescription('为crm_customer表所有记录生成唯一code码,分批处理'); } protected function execute(InputInterface $input, OutputInterface $output): int { $batchSize = 1000; $total = Customer::withTrashed()->where('code','')->count(); $output->writeln("总计需处理:$total 条记录"); $processed = 0; do { // 查询一批未生成code的记录 $customers = Customer::withTrashed()->where('code','')->limit($batchSize)->get(); if ($customers->isEmpty()) { break; } // Eloquent 批量处理 foreach ($customers as $customer) { // 生成唯一16位code,CM+14位 $unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14)); $code = 'CM' . $unique; // 防止极小概率重复 while (Customer::where('code', $code)->exists()) { $unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14)); $code = 'CM' . $unique; } $created_at = $customer->created_at->getTimestamp(); $obtain = $created_at > strtotime('2025-07-29')?$created_at:strtotime('2025-07-29'); $customer->code = $code; $customer->obtain = $obtain; $customer->save(); $processed++; } $output->writeln("已处理:$processed / $total"); } while (true); $output->writeln('全部处理完成!'); return self::SUCCESS; } }