diff --git a/app/Console/Commands/UpdateUserTalentTags.php b/app/Console/Commands/UpdateUserTalentTags.php index d34fdff..06be251 100644 --- a/app/Console/Commands/UpdateUserTalentTags.php +++ b/app/Console/Commands/UpdateUserTalentTags.php @@ -16,7 +16,7 @@ class UpdateUserTalentTags extends Command * * @var string */ - protected $signature = 'update:user-talent-tags {--clean-duplicates : 清理已存在的重复标签}'; + protected $signature = 'update:user-talent-tags {--clean-duplicates : 清理已存在的重复标签} {--only-clean : 仅清理重复标签,不执行更新}'; /** * The console command description. @@ -32,6 +32,12 @@ class UpdateUserTalentTags extends Command */ public function handle() { + // 如果指定了仅清理选项,只执行清理后退出 + if ($this->option('only-clean')) { + $this->cleanDuplicateTags(); + return 0; + } + // 如果指定了清理重复标签选项,先执行清理 if ($this->option('clean-duplicates')) { $this->cleanDuplicateTags(); @@ -209,6 +215,7 @@ class UpdateUserTalentTags extends Command $cleanedCount = 0; $totalCleaned = 0; + $unchangedCount = 0; DB::beginTransaction(); @@ -216,14 +223,30 @@ class UpdateUserTalentTags extends Command foreach ($users as $user) { $originalTags = $user->talent_tags; - // 将标签转换为数组 - $tagsArray = array_filter(array_map('trim', explode(',', $originalTags))); + // 将标签转换为数组,去除空值 + $tagsArray = array_filter(array_map('trim', explode(',', $originalTags)), function ($tag) { + return !empty($tag); + }); + + // 去重(保持顺序,使用严格比较) + $uniqueTagsArray = []; + $seen = []; + foreach ($tagsArray as $tag) { + $tag = trim($tag); + if (!empty($tag) && !in_array($tag, $seen, true)) { + $uniqueTagsArray[] = $tag; + $seen[] = $tag; + } + } + + // 重新索引数组 + $uniqueTagsArray = array_values($uniqueTagsArray); - // 去重 - $uniqueTagsArray = array_values(array_unique($tagsArray)); + // 如果去重后数量减少或顺序改变,需要更新 + $originalCount = count($tagsArray); + $uniqueCount = count($uniqueTagsArray); - // 如果去重后数量减少,说明有重复 - if (count($tagsArray) > count($uniqueTagsArray)) { + if ($originalCount !== $uniqueCount || implode(',', $tagsArray) !== implode(',', $uniqueTagsArray)) { $cleanedTags = implode(',', $uniqueTagsArray); $user->talent_tags = $cleanedTags; $user->save(); @@ -233,7 +256,9 @@ class UpdateUserTalentTags extends Command $this->info(" 到: {$cleanedTags}"); $cleanedCount++; - $totalCleaned += (count($tagsArray) - count($uniqueTagsArray)); + $totalCleaned += ($originalCount - $uniqueCount); + } else { + $unchangedCount++; } } @@ -244,11 +269,13 @@ class UpdateUserTalentTags extends Command $this->info('清理完成!'); $this->info("清理了 {$cleanedCount} 个用户的重复标签"); $this->info("共移除 {$totalCleaned} 个重复标签"); + $this->info("无需清理: {$unchangedCount} 个用户"); $this->info('========================================'); $this->info(''); } catch (\Exception $e) { DB::rollBack(); $this->error('清理重复标签时发生错误: ' . $e->getMessage()); + $this->error('错误堆栈: ' . $e->getTraceAsString()); throw $e; } }