Laravel 8 外鍵約束

2021-07-19 11:20 更新

Laravel 還支持創(chuàng)建用于在數(shù)據(jù)庫層中的強制引用完整性的外鍵約束。例如,讓我們在 posts 表上定義一個引用 users 表的 id 字段的 user_id 字段:

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
}); 

由于這種外鍵約束的定義方式過于繁復(fù),Laravel 額外提供了更簡潔的方法,這些方法使用約定來提供更好的開發(fā)人員體驗。上面的示例還可以這么寫:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
}); 

foreignId 方法是 unsignedBigInteger 的別名,而 constrained 方法將使用約定來確定所引用的表名和列名。如果表名與約定不匹配,可以通過將表名作為參數(shù)傳遞給 constrained 方法來指定表名:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained('users');
}); 

你可以為約束的「on delete」和「on update」屬性指定所需的操作:

$table->foreignId('user_id')
      ->constrained()
      ->onDelete('cascade'); 

當(dāng)使用任意 字段修飾符 的時候,必須在調(diào)用 constrained 之前調(diào)用:

$table->foreignId('user_id')
      ->nullable()
      ->constrained(); 

要刪除一個外鍵,你需要使用 dropForeign 方法,將要刪除的外鍵約束作為參數(shù)傳遞。外鍵約束采用的命名方式與索引相同。即,將數(shù)據(jù)表名稱和約束的字段連接起來,再加上 _foreign 后綴:

$table->dropForeign('posts_user_id_foreign'); 

或者,可以給 dropForeign 方法傳遞一個數(shù)組,該數(shù)組包含要刪除的外鍵的列名。數(shù)組將根據(jù) Laravel 的 Schema 生成器使用的約束名稱約定自動轉(zhuǎn)換:

$table->dropForeign(['user_id']); 

你可以在遷移文件中使用以下方法來開啟或關(guān)閉外鍵約束:

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints(); 

注意:SQLite 默認(rèn)禁用外鍵約束。使用 SQLite 時,請確保在數(shù)據(jù)庫配置中啟用 啟用外鍵支持 然后再嘗試在遷移中創(chuàng)建它們。另外,SQLite 只在創(chuàng)建表時支持外鍵,并且 在修改表時就不會了。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號