master
cody 2 months ago
parent a2f902a13c
commit ddd02fc540

@ -16,7 +16,7 @@ class UpdateUserTalentTags extends Command
*
* @var string
*/
protected $signature = 'update:user-talent-tags {--clean-duplicates : 清理已存在的重复标签} {--only-clean : 仅清理重复标签,不执行更新}';
protected $signature = 'update:user-talent-tags {--clean-duplicates : 清理已存在的重复标签}';
/**
* The console command description.
@ -32,12 +32,6 @@ class UpdateUserTalentTags extends Command
*/
public function handle()
{
// 如果指定了仅清理选项,只执行清理后退出
if ($this->option('only-clean')) {
$this->cleanDuplicateTags();
return 0;
}
// 如果指定了清理重复标签选项,先执行清理
if ($this->option('clean-duplicates')) {
$this->cleanDuplicateTags();
@ -215,7 +209,6 @@ class UpdateUserTalentTags extends Command
$cleanedCount = 0;
$totalCleaned = 0;
$unchangedCount = 0;
DB::beginTransaction();
@ -223,30 +216,14 @@ class UpdateUserTalentTags extends Command
foreach ($users as $user) {
$originalTags = $user->talent_tags;
// 将标签转换为数组,去除空值
$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;
}
}
// 将标签转换为数组
$tagsArray = array_filter(array_map('trim', explode(',', $originalTags)));
// 重新索引数组
$uniqueTagsArray = array_values($uniqueTagsArray);
// 去重
$uniqueTagsArray = array_values(array_unique($tagsArray));
// 如果去重后数量减少或顺序改变,需要更新
$originalCount = count($tagsArray);
$uniqueCount = count($uniqueTagsArray);
if ($originalCount !== $uniqueCount || implode(',', $tagsArray) !== implode(',', $uniqueTagsArray)) {
// 如果去重后数量减少,说明有重复
if (count($tagsArray) > count($uniqueTagsArray)) {
$cleanedTags = implode(',', $uniqueTagsArray);
$user->talent_tags = $cleanedTags;
$user->save();
@ -256,9 +233,7 @@ class UpdateUserTalentTags extends Command
$this->info(" 到: {$cleanedTags}");
$cleanedCount++;
$totalCleaned += ($originalCount - $uniqueCount);
} else {
$unchangedCount++;
$totalCleaned += (count($tagsArray) - count($uniqueTagsArray));
}
}
@ -269,13 +244,11 @@ 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;
}
}

Loading…
Cancel
Save