From c0a22e875cf7a156e9c75f6e77d7c079d4ae5861 Mon Sep 17 00:00:00 2001 From: w33b Date: Mon, 22 Sep 2025 00:18:22 +0200 Subject: [PATCH] Fix duplicate download entries and add constraint --- ...d_unique_constraint_to_downloads_table.php | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 database/migrations/2025_09_21_215923_add_unique_constraint_to_downloads_table.php 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']); + }); + } +};