我有两个表具有一对一的关系,由外键约束设置。我想将onDelete
规则设置为“设置默认值”,这意味着当删除外部表上的一行时,引用值将恢复为其默认值。这是我的代码:
游览表:
Schema::create('tours', function (Blueprint $table) {
$table->increments('id')->unsigned()->index();
$table->integer('grade')->unsigned()->default(1);
$table->timestamps();
});
成绩表:Schema::create('grades', function(Blueprint $table){
$table->increments('id')->unsigned()->index();
$table->string('name');
$table->timestamps();
});
设置外键:Schema::table('tours', function (Blueprint $table) {
$table->foreign('grade')->references('id')->on('grades')->onDelete('set default');
});
当我运行迁移时,它没有错误。但是,看一下HeidiSQL中的表,它不能正常工作。外键已设置,但是onDelete属性仅显示“NO ACTION”。随后,当我删除成绩表中的一行时,出现外键约束错误。
我究竟做错了什么?
最佳答案
已经有一段时间了,但这取决于数据库使用的引擎。如果您使用InnoDB或NDB,,则语法将被解析,但会忽略。
检查MySQL文档的this section:
Referential Actions
...
SET DEFAULT
: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions containingON DELETE SET DEFAULT
orON UPDATE SET DEFAULT
clauses.
如果适合您的需求,可以改用
SET NULL
。如果没有,那么您可以创建一个observer来为您执行此操作。
关于mysql - Laravel Schema onDelete设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41302495/