Laravel :: 更新外键的最佳方式

2022-08-30 12:16:09

我有此迁移文件

Schema::create('table_one', function(Blueprint $table) 
{ 
    $table->increments('id'); 
    $table->string('name'); 
    $table->integer('table_two_id')->unsigned(); 
    $table->foreign('table_two_id')->references('id')->on('table_two'); 
    $table->timestamps(); 
});

我想更新它 - >onDelete('cascade');

$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');

最好的方法是什么?

有没有类似 ->change() 的东西;

谢谢


答案 1

删除外键,然后再次添加并运行迁移。

public function up()
{
    Schema::table('table_one', function (Blueprint $table) {
        $table->dropForeign(['table_two_id']);

        $table->foreign('table_two_id')
            ->references('id')
            ->on('table_two')
            ->onDelete('cascade');
    });
}

答案 2

Christopher K.是对的,在Laravel文档上说:

若要删除外键,可以使用 dropForeign 方法。外键约束使用与索引相同的命名约定。因此,我们将连接约束中的表名和列,然后在名称后缀“_foreign”

$table->dropForeign('posts_user_id_foreign'); 

或者,您可以传递一个数组值,该值在删除时将自动使用常规约束名称:

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

https://laravel.com/docs/5.7/migrations#foreign-key-constraints


推荐