阅读(2355) (0)

Laravel 8 外键约束

2021-07-07 10:18:40 更新

Laravel 还支持创建用于在数据库层中的强制引用完整性的外键约束。例如,让我们在 posts 表上定义一个引用 users 表的 id 字段的 user_id 字段:

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

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

由于这种外键约束的定义方式过于繁复,Laravel 额外提供了更简洁的方法,这些方法使用约定来提供更好的开发人员体验。上面的示例还可以这么写:

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

foreignId 方法是 unsignedBigInteger 的别名,而 constrained 方法将使用约定来确定所引用的表名和列名。如果表名与约定不匹配,可以通过将表名作为参数传递给 constrained 方法来指定表名:

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

你可以为约束的「on delete」和「on update」属性指定所需的操作:

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

当使用任意 字段修饰符 的时候,必须在调用 constrained 之前调用:

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

要删除一个外键,你需要使用 dropForeign 方法,将要删除的外键约束作为参数传递。外键约束采用的命名方式与索引相同。即,将数据表名称和约束的字段连接起来,再加上 _foreign 后缀:

$table->dropForeign('posts_user_id_foreign'); 

或者,可以给 dropForeign 方法传递一个数组,该数组包含要删除的外键的列名。数组将根据 Laravel 的 Schema 生成器使用的约束名称约定自动转换:

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

你可以在迁移文件中使用以下方法来开启或关闭外键约束:

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints(); 

注意:SQLite 默认禁用外键约束。使用 SQLite 时,请确保在数据库配置中启用 启用外键支持 然后再尝试在迁移中创建它们。另外,SQLite 只在创建表时支持外键,并且 在修改表时就不会了