FillTelegramAccounts.php 1.5 KB

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