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

问题描述 投票:13回答:2

我有这个迁移文件

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();

谢谢

php database laravel laravel-5.1
2个回答
26
投票

删除外键然后再次添加它并运行migrate。

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');
    });
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.