报错原因:
Laravel 运行迁移文件时报错(添加外键约束时报错)
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'setnull' at line 1 (SQL: alter table `products` add constraint `products_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) on delete setnull)
已经给出提示setnull附近语法错误
解决1064这类问题基本上都是sql语法错误,关键字冲突,还有就是格式问题了,遇到类似问题仔细查看给出的提示附近的语法与格式
报错截图

报错的代码:
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->unsignedBigInteger('category_id')->nullable()->after('id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('setnull');
});
}
改正后的代码(将setnull改为set null,中间加一个空格)
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->unsignedBigInteger('category_id')->nullable()->after('id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});
}
还有就是csdn的编辑器牛逼:将语言设置为php,好像有自动检查错误的功能?

本文解决了一个关于Laravel中添加外键约束时出现的SQL语法错误问题,具体表现为setnull附近的语法错误。通过调整onDelete方法中的参数格式,成功解决了报错。
1080

被折叠的 条评论
为什么被折叠?



