info('Starting optimized department migration...'); $legacyConn = DB::connection('mysql_second'); $query = $legacyConn->table('agencies'); $totalCount = $query->count(); if ($totalCount === 0) { $this->warn('No departments found in legacy database.'); return; } $this->info("Found {$totalCount} legacy department records."); // Cache existing IDs for faster processing $this->migratedIds = DB::table('departments')->pluck('id')->flip()->all(); $query->orderBy('id')->chunk(50, function ($chunk) { foreach ($chunk as $legacy) { $this->processDepartment($legacy); } }); $this->newLine(); $this->info('Department migration completed successfully!'); } /** * Process a single legacy department record. */ private function processDepartment($legacy): void { $idText = "[#{$legacy->id}]"; $idOutput = $legacy->deleted_at ? "{$idText}" : "{$idText}"; $this->output->write("{$idOutput} Processing: ".Str::limit($legacy->name, 40).'... '); try { DB::table('departments')->updateOrInsert( ['id' => $legacy->id], [ 'name' => $legacy->name, 'alias' => Str::limit($legacy->name, 20, ''), 'is_active' => IsActive::ACTIVE->value, 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now(), 'deleted_at' => $legacy->deleted_at, ] ); $this->output->writeln('DONE'); } catch (\Exception $e) { $this->output->writeln('FAILED: '.$e->getMessage().''); } } }