master
cody 3 days ago
parent 424c75454f
commit 638e164f4e

@ -1,78 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
class NormalizeUserBirthdayMonth extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'users:normalize-birthday-month {--dry-run : 仅预览将被修复的数据,不实际写库}';
/**
* The console command description.
*
* @var string
*/
protected $description = '将用户表中形如 YYYY-MM-01 的生日还原为 YYYY-MM';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$dryRun = (bool) $this->option('dry-run');
$query = User::query()
->whereNotNull('birthday')
->where('birthday', 'like', '____-__-01');
$total = (clone $query)->count();
if ($total === 0) {
$this->info('未找到需要修复的生日数据');
return self::SUCCESS;
}
$this->info(($dryRun ? '预览' : '开始修复') . " {$total} 条生日数据");
$updated = 0;
$previewed = 0;
$query->orderBy('id')->chunkById(200, function ($users) use ($dryRun, &$updated, &$previewed) {
foreach ($users as $user) {
$normalizedBirthday = substr($user->birthday, 0, 7);
if ($dryRun) {
if ($previewed < 20) {
$this->line("user_id={$user->id} {$user->birthday} => {$normalizedBirthday}");
}
$previewed++;
continue;
}
$user->birthday = $normalizedBirthday;
$user->save();
$updated++;
}
});
if ($dryRun) {
if ($previewed > 20) {
$this->line('仅展示前 20 条预览结果');
}
$this->info("预览完成,共 {$total} 条待修复");
return self::SUCCESS;
}
$this->info("修复完成,共更新 {$updated} 条生日数据");
return self::SUCCESS;
}
}
Loading…
Cancel
Save