我正在尝试在Laravel中创建外键。但是,当我使用Artisan迁移表时,出现以下错误。
Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规错误: 1215无法添加外键约束(SQL:alter table
posts
add 约束posts_category_id_foreign
外键(category_id
) 引用categories
(id
))
帖子迁移
Schema::create('posts', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('title');
$table->string('slug')->unique();
$table->longText('content');
$table->string('image')->nullable();
$table->uuid('author_id');
$table->uuid('category_id');
$table->timestamps();
$table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});
类别迁移
Schema::create('categories', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('slug')->unique();
$table->uuid('parent')->nullable();
});
答案 0 :(得分:2)
在您的posts
模式中,您将删除时将author_id
和category_id
设置为空,但是没有将这些字段设置为可空。将定义更改为:
$table->uuid('author_id')->nullable();
$table->uuid('category_id')->nullable();
应该这样做。
答案 1 :(得分:1)
将外键声明拆分为自己的Schema方法...
我不了解问题的原因,但是这样做一直对我有用。
Schema::create('posts', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('title');
$table->string('slug')->unique();
$table->longText('content');
$table->string('image')->nullable();
$table->uuid('author_id');
$table->uuid('category_id');
$table->timestamps();
});
Schema::table('posts', function(Blueprint $table) {
$table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});