diff --git a/database/migrations/2025_09_21_215923_add_unique_constraint_to_downloads_table.php b/database/migrations/2025_09_21_215923_add_unique_constraint_to_downloads_table.php new file mode 100644 index 0000000..2dab96b --- /dev/null +++ b/database/migrations/2025_09_21_215923_add_unique_constraint_to_downloads_table.php @@ -0,0 +1,54 @@ +forceDelete(); + + # Remove duplicate entries + $duplicates = DB::table('downloads') + ->select('episode_id', 'type', DB::raw('COUNT(*) as count')) + ->groupBy('episode_id', 'type') + ->having('count', '>', 1) + ->get(); + + foreach ($duplicates as $duplicate) { + // Find all rows for this episode_id and type + $rows = DB::table('downloads') + ->where('episode_id', $duplicate->episode_id) + ->where('type', $duplicate->type) + ->orderBy('count', 'desc') // Order by count to delete the ones with the lower count + ->get(); + + // Delete the rows with lower counts, keeping the one with the highest count + $rows->skip(1)->each(function ($row) { + DB::table('downloads')->where('id', $row->id)->delete(); + }); + } + + Schema::table('downloads', function (Blueprint $table) { + $table->unique(['episode_id', 'type']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('downloads', function (Blueprint $table) { + $table->dropUnique(['episode_id', 'type']); + }); + } +};