| 123456789101112131415161718192021222324252627282930313233343536373839 |
- <?php
- namespace App\Console\Commands;
- use App\Models\User;
- use Illuminate\Console\Command;
- class FillTelegramAccounts extends Command
- {
- protected $signature = 'users:fill-tg-account {--dry-run : 只打印,不写库}';
- protected $description = '给 from=-1(Telegram 进来)且没有 account 的用户补 account:tg + 随机数字,唯一';
- public function handle(): int
- {
- $dry = (bool)$this->option('dry-run');
- $count = 0;
- $query = User::query()->where('from', -1)
- ->where(fn ($q) => $q->whereNull('account')->orWhere('account', ''));
- // chunkById:更新后行会脱离筛选条件,普通 chunk 会跳页
- $query->select('id', 'member_id', 'account')->chunkById(500, function ($users) use ($dry, &$count) {
- foreach ($users as $user) {
- $account = User::generateTgAccount();
- if (!$dry) {
- // 只在 account 仍为空时写入,避免覆盖并发产生的值
- $updated = User::where('id', $user->id)
- ->where(fn ($q) => $q->whereNull('account')->orWhere('account', ''))
- ->update(['account' => $account]);
- if (!$updated) continue;
- }
- $count++;
- $this->line("{$user->id} ({$user->member_id}): {$account}");
- }
- });
- $this->info(($dry ? '[dry-run] 将更新 ' : '已更新 ') . "{$count} 个用户");
- return self::SUCCESS;
- }
- }
|