gpt4 book ai didi

mysql - Laravel Schema onDelete设置默认值

转载 作者:行者123 更新时间:2023-12-03 16:25:45 26 4
gpt4 key购买 nike

我有两个表具有一对一的关系,由外键约束设置。我想将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”。
随后,当我删除成绩表中的一行时,出现外键约束错误。
我究竟做错了什么?

最佳答案

已经有一段时间了,但这取决于数据库使用的引擎。如果您使用InnoDBNDB,则语法将被解析,但会忽略

检查MySQL文档的this section:

Referential Actions

...

SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.



如果适合您的需求,可以改用 SET NULL。如果没有,那么您可以创建一个 observer来为您执行此操作。

关于mysql - Laravel Schema onDelete设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41302495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com