UnlinkAgentOwners.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\DB;
  5. class UnlinkAgentOwners extends Command
  6. {
  7. protected $signature = 'agent:unlink-owners
  8. {--username= : 只处理指定代理账号}
  9. {--all : 处理全部代理账号}
  10. {--write : 实际解除关联,默认只预览}';
  11. protected $description = '预览或清理代理账号历史保存的会员身份关联';
  12. public function handle(): int
  13. {
  14. $username = trim((string) $this->option('username'));
  15. $all = $this->option('all');
  16. $write = $this->option('write');
  17. if ($this->input->hasParameterOption('--username') && ($username === '' || $all)) {
  18. $this->error('请填写代理账号,或单独使用 --all');
  19. return self::INVALID;
  20. }
  21. if ($write && $username === '' && !$all) {
  22. $this->error('写入时请指定 --username 或 --all');
  23. return self::INVALID;
  24. }
  25. $connection = DB::connection();
  26. $table = $connection->getTablePrefix() . 'agents';
  27. $this->info('模式:' . ($write ? '写入' : '预览'));
  28. $this->line('数据库:' . $connection->getDatabaseName());
  29. $this->line('处理原因:代理账号独立管理,清除历史会员关联。');
  30. $this->line("修改范围:{$table}.owner_user_id → NULL");
  31. $query = $connection->table('agents')->whereNotNull('owner_user_id');
  32. if ($username !== '') $query->where('username', $username);
  33. $process = function () use ($query, $write) {
  34. $targets = (clone $query)->orderBy('id');
  35. if ($write) $targets->lockForUpdate();
  36. $rows = $targets->get(['id', 'username', 'owner_user_id']);
  37. $updated = $write && $rows->isNotEmpty()
  38. ? $query->whereIntegerInRaw('id', $rows->pluck('id')->all())->update(['owner_user_id' => null])
  39. : 0;
  40. return [$rows, $updated];
  41. };
  42. [$rows, $updated] = $write ? $connection->transaction($process) : $process();
  43. $this->line('检查到关联:' . $rows->count() . ' 条');
  44. if ($rows->isNotEmpty()) {
  45. $this->table(['表', '代理 ID', '代理账号', '字段', '原值', '新值'], $rows->map(
  46. fn ($row) => [$table, $row->id, $row->username, 'owner_user_id', $row->owner_user_id, 'NULL']
  47. )->all());
  48. }
  49. $this->line("实际更新:{$updated} 条");
  50. return self::SUCCESS;
  51. }
  52. }