From 429a3a99fde25de00703579fbfd1eb3c8acf456f Mon Sep 17 00:00:00 2001 From: Sholahuddin Al Ayubi Date: Tue, 23 Dec 2025 16:56:09 +0700 Subject: [PATCH] feat(migration): add parent_id column and foreign key to branches table with checks --- ...074721_add_parent_id_to_branches_table.php | 54 ++++++++++++++++--- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/database/migrations/2025_05_18_074721_add_parent_id_to_branches_table.php b/database/migrations/2025_05_18_074721_add_parent_id_to_branches_table.php index 5b67079..edabcf1 100644 --- a/database/migrations/2025_05_18_074721_add_parent_id_to_branches_table.php +++ b/database/migrations/2025_05_18_074721_add_parent_id_to_branches_table.php @@ -3,18 +3,30 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Facades\DB; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('branches', function (Blueprint $table) { - $table->unsignedBigInteger('parent_id')->nullable()->after('name'); - $table->foreign('parent_id')->references('id')->on('branches')->onDelete('set null'); + // Tambah kolom parent_id jika belum ada + if (!Schema::hasColumn('branches', 'parent_id')) { + $table->unsignedBigInteger('parent_id')->nullable()->after('name'); + } }); + + // Tambah foreign key jika belum ada + if (!$this->foreignKeyExists('branches', 'branches_parent_id_foreign')) { + Schema::table('branches', function (Blueprint $table) { + $table->foreign('parent_id', 'branches_parent_id_foreign') + ->references('id') + ->on('branches') + ->onDelete('set null'); + }); + } } /** @@ -22,9 +34,39 @@ return new class extends Migration */ public function down(): void { + // Drop foreign key jika ada + if ($this->foreignKeyExists('branches', 'branches_parent_id_foreign')) { + Schema::table('branches', function (Blueprint $table) { + $table->dropForeign('branches_parent_id_foreign'); + }); + } + + // Drop kolom jika ada Schema::table('branches', function (Blueprint $table) { - $table->dropForeign(['parent_id']); - $table->dropColumn('parent_id'); + if (Schema::hasColumn('branches', 'parent_id')) { + $table->dropColumn('parent_id'); + } }); } + + /** + * Cek apakah foreign key exists + */ + private function foreignKeyExists(string $table, string $name): bool + { + $conn = Schema::getConnection(); + $dbName = $conn->getDatabaseName(); + + $result = DB::select( + "SELECT CONSTRAINT_NAME + FROM information_schema.TABLE_CONSTRAINTS + WHERE TABLE_SCHEMA = ? + AND TABLE_NAME = ? + AND CONSTRAINT_NAME = ? + AND CONSTRAINT_TYPE = 'FOREIGN KEY'", + [$dbName, $table, $name] + ); + + return count($result) > 0; + } };