diff --git a/app/Console/Commands/DedupTags.php b/app/Console/Commands/DedupTags.php new file mode 100644 index 0000000..3300e59 --- /dev/null +++ b/app/Console/Commands/DedupTags.php @@ -0,0 +1,113 @@ +option('dry-run')) { + $this->warn('dry-runモードで実行します。'); + } else { + if (!$this->confirm('dry-runオプションが付いてないけど、本当に実行しますか?')) { + return; + } + } + + DB::transaction(function () { + $duplicatedTags = DB::table('tags') + ->select('name', DB::raw('count(*)')) + ->groupBy('name') + ->having(DB::raw('count(*)'), '>=', 2) + ->get(); + + $this->info($duplicatedTags->count() . ' duplicated tags found.'); + + foreach ($duplicatedTags as $tag) { + $this->line('Tag name: ' . $tag->name); + + $tagIds = Tag::where('name', $tag->name)->orderBy('id')->pluck('id'); + $newId = $tagIds->first(); + $dropIds = $tagIds->slice(1); + + $this->line(' New ID: ' . $newId); + $this->line(' Drop IDs: ' . $dropIds->implode(', ')); + + if ($this->option('dry-run')) { + continue; + } + + // 同じタグ名でIDが違うものについて、全て統一する + foreach (['ejaculation_tag', 'metadata_tag'] as $table) { + DB::table($table) + ->whereIn('tag_id', $dropIds) + ->update(['tag_id' => $newId]); + } + DB::table('tags')->whereIn('id', $dropIds)->delete(); + + // 統一した上で、重複しているレコードを削除する + DB::delete( + << 1 +) +SQL + ); + DB::delete( + << 1 +) +SQL + ); + } + }); + + $this->info('Done!'); + } +} diff --git a/database/migrations/2020_02_22_164304_add_unique_constraint_to_tag_relations.php b/database/migrations/2020_02_22_164304_add_unique_constraint_to_tag_relations.php new file mode 100644 index 0000000..b8d6f50 --- /dev/null +++ b/database/migrations/2020_02_22_164304_add_unique_constraint_to_tag_relations.php @@ -0,0 +1,38 @@ +unique(['ejaculation_id', 'tag_id']); + }); + Schema::table('metadata_tag', function (Blueprint $table) { + $table->unique(['metadata_url', 'tag_id']); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('ejaculation_tag', function (Blueprint $table) { + $table->dropUnique(['ejaculation_id', 'tag_id']); + }); + Schema::table('metadata_tag', function (Blueprint $table) { + $table->dropUnique(['metadata_url', 'tag_id']); + }); + } +}