| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\DB;
- class UnlinkAgentOwners extends Command
- {
- protected $signature = 'agent:unlink-owners
- {--username= : 只处理指定代理账号}
- {--all : 处理全部代理账号}
- {--write : 实际解除关联,默认只预览}';
- protected $description = '预览或清理代理账号历史保存的会员身份关联';
- public function handle(): int
- {
- $username = trim((string) $this->option('username'));
- $all = $this->option('all');
- $write = $this->option('write');
- if ($this->input->hasParameterOption('--username') && ($username === '' || $all)) {
- $this->error('请填写代理账号,或单独使用 --all');
- return self::INVALID;
- }
- if ($write && $username === '' && !$all) {
- $this->error('写入时请指定 --username 或 --all');
- return self::INVALID;
- }
- $connection = DB::connection();
- $table = $connection->getTablePrefix() . 'agents';
- $this->info('模式:' . ($write ? '写入' : '预览'));
- $this->line('数据库:' . $connection->getDatabaseName());
- $this->line('处理原因:代理账号独立管理,清除历史会员关联。');
- $this->line("修改范围:{$table}.owner_user_id → NULL");
- $query = $connection->table('agents')->whereNotNull('owner_user_id');
- if ($username !== '') $query->where('username', $username);
- $process = function () use ($query, $write) {
- $targets = (clone $query)->orderBy('id');
- if ($write) $targets->lockForUpdate();
- $rows = $targets->get(['id', 'username', 'owner_user_id']);
- $updated = $write && $rows->isNotEmpty()
- ? $query->whereIntegerInRaw('id', $rows->pluck('id')->all())->update(['owner_user_id' => null])
- : 0;
- return [$rows, $updated];
- };
- [$rows, $updated] = $write ? $connection->transaction($process) : $process();
- $this->line('检查到关联:' . $rows->count() . ' 条');
- if ($rows->isNotEmpty()) {
- $this->table(['表', '代理 ID', '代理账号', '字段', '原值', '新值'], $rows->map(
- fn ($row) => [$table, $row->id, $row->username, 'owner_user_id', $row->owner_user_id, 'NULL']
- )->all());
- }
- $this->line("实际更新:{$updated} 条");
- return self::SUCCESS;
- }
- }
|