Laravel 5.x 中 onUpdate / onDelete 的可用操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39518162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Available actions for onUpdate / onDelete in Laravel 5.x
提问by bobD
As mentioned in here, we can use the word cascadewhen making a relation in migrations
but I wonder they didn't say anything about other actions when deletingor updatinga foreign key
so I'm not sure if there is such thing or not:
正如这里提到的,我们可以cascade在迁移中建立关系时使用这个词,
但我想知道他们没有说任何关于 whendeleting或updating外键的其他操作,
所以我不确定是否有这样的事情:
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('set null');
//->onDelete('set_null');
//->onDelete('setNull');
or the same thing about onUpdateand about no actionjust like the phpMyAdmin
或同样的事情onUpdate,no action就像phpMyAdmin
thanks
谢谢
回答by Rafael Berro
You can do all the options mentioned in phpmyadminthis way:
您可以通过phpmyadmin这种方式执行所有提到的选项:
$table->...->onDelete('CASCADE');
$table->...->onDelete('SET NULL');
$table->...->onDelete('RESTRICT');
// do not call the onDelete() method if you want the RESTRICT option.
You have to make sure you set the foreign key field as nullable:
您必须确保将外键字段设置为可为空:
$table->...->unsigned()->nullable();
回答by Jaspal Singh
Referring to the source code:
参考源代码:
`vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php` in the function compileForeign()
It just appends whatever you pass in to the table query.
它只是将您传入的任何内容附加到表查询中。
if (! is_null($command->onDelete)) {
$sql .= " on delete {$command->onDelete}";
}
if (! is_null($command->onUpdate)) {
$sql .= " on update {$command->onUpdate}";
}
So, make sure you pass one of the following: "cascade", "no action", "restrict", or "set null"
因此,请确保传递以下其中一项:“cascade”、“no action”、“restrict”或“set null”
NOTE: Do NOTuse underscores in the actions like "set_null" and "no_action"
注意:请不要在这样的行动中使用下划线“set_null”和“no_action”


