浏览代码

Add cascade delete on AuthLog table

Bubka 1 年之前
父节点
当前提交
99bf9d7d80

+ 9 - 0
database/migrations/2024_04_14_082519_create_auth_logs_table.php

@@ -41,11 +41,20 @@ return new class extends Migration
             $table->boolean('cleared_by_user')->default(false);
             $table->string('guard', 40)->nullable();
             $table->string('login_method', 40)->nullable();
+
+            $table->foreign('authenticatable_id')->references('id')->on('users')->cascadeOnDelete();
         });
     }
 
     public function down(): void
     {
+        Schema::whenTableHasColumn('auth_logs', 'authenticatable_id', function (Blueprint $table) {
+            // cannot drop foreign keys in SQLite:
+            if (DB::getDriverName() !== 'sqlite') {
+                $table->dropForeign(['authenticatable_id']);
+            }
+        });
+
         Schema::dropIfExists('auth_logs');
     }
 };

+ 5 - 0
tests/Feature/Models/UserModelTest.php

@@ -2,6 +2,7 @@
 
 namespace Tests\Feature\Models;
 
+use App\Models\AuthLog;
 use App\Models\Group;
 use App\Models\TwoFAccount;
 use App\Models\User;
@@ -113,6 +114,7 @@ class UserModelTest extends FeatureTestCase
     {
         $user = User::factory()->create();
         TwoFAccount::factory()->for($user)->create();
+        AuthLog::factory()->for($user, 'authenticatable')->create();
         Group::factory()->for($user)->create();
 
         DB::table('webauthn_credentials')->insert([
@@ -154,6 +156,9 @@ class UserModelTest extends FeatureTestCase
         $this->assertDatabaseMissing(config('auth.passwords.users.table'), [
             'email' => $user->email,
         ]);
+        $this->assertDatabaseMissing('auth_logs', [
+            'authenticatable_id' => $user->id,
+        ]);
     }
 
     /**