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!'); } }