Laravel 5.x中onUpdate/onDelete的可用操作

bob*_*obD 10 laravel laravel-5 laravel-migrations

正如这里所提到的,我们可以cascade在迁移中建立关系时使用这个词,
但我不知道他们在外键deletingupdating外键时没有说出其他动作,

所以我不确定是否有这样的事情:

$table->foreign('user_id')
  ->references('id')->on('users')
  ->onDelete('set null');
  //->onDelete('set_null');
  //->onDelete('setNull');
Run Code Online (Sandbox Code Playgroud)

或者同样的事情onUpdate和关于no action就像phpMyAdmin

在此输入图像描述


谢谢

Raf*_*rro 18

您可以通过phpmyadmin这种方式执行所有选项:

$table->...->onDelete('CASCADE');
$table->...->onDelete('SET NULL');
$table->...->onDelete('RESTRICT');

// do not call the onDelete() method if you want the NO ACTION option.
Run Code Online (Sandbox Code Playgroud)

您必须确保将外键字段设置为可为空:

$table->...->unsigned()->nullable();
Run Code Online (Sandbox Code Playgroud)


Jas*_*ngh 6

参考源码:

`vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php` in the function compileForeign()
Run Code Online (Sandbox Code Playgroud)

它只是将您传入的任何内容附加到表查询中。

    if (! is_null($command->onDelete)) {
        $sql .= " on delete {$command->onDelete}";
    }

    if (! is_null($command->onUpdate)) {
        $sql .= " on update {$command->onUpdate}";
    }
Run Code Online (Sandbox Code Playgroud)

因此,请确保传递以下其中一项:“cascade”、“no action”、“restrict”或“set null”

注意:请勿“set_null”和“no_action”等操作中使用下划线