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

Yev*_*yev 18 php database laravel laravel-5.1

我有这个迁移文件

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(); 
});
Run Code Online (Sandbox Code Playgroud)

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

$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

是否有类似- > change();

谢谢

Bor*_*lis 29

删除外键然后再次添加它并运行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');
    });
}
Run Code Online (Sandbox Code Playgroud)


小智 8

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

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

$table->dropForeign('posts_user_id_foreign'); 
Run Code Online (Sandbox Code Playgroud)

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

$table->dropForeign(['user_id']);
Run Code Online (Sandbox Code Playgroud)

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


Asi*_*kib 5

  1. 跑步composer require doctrine/dbal
  2. 在您的迁移文件中,执行以下操作:
     Schema::table('table_one', function (Blueprint $table) {
         $table->foreignId('table_two_id')
               ->change()
               ->constrained('table_two')
               ->onDelete('cascade');
     });
    
    Run Code Online (Sandbox Code Playgroud)
  3. 跑步php artisan migrate

  • 错误`SQLSTATE[23000]: 违反完整性约束: 1022 无法写入;通过重新定义“constrained”更新外键时,会引发表中的重复键...,因此只需删除约束并说出您只需要更新并使用“->change()”链接它的内容即可。就我而言,我刚刚将外键更新为可为空,我不需要再次重新定义约束,因为它应该在创建迁移中调用,而不是更改迁移,除非您想将约束更改为另一个表。 (2认同)

小智 5

您需要删除

public function up() {
    Schema::table('<tableName>', function (Blueprint $table) {
        $table->dropForeign('<FK-name>');
        $table->dropColumn('<FK-columnName>');
    });
    Schema::table('<tableName>', function (Blueprint $table) {
        $table->foreignId('<FK-columnName>')->constrained()->cascadeOnDelete();
    });
}
Run Code Online (Sandbox Code Playgroud)

有两个查询。

这在 Laravel 8 中工作