[英]Migration: Cannot add foreign key constraint in Laravel 6
I'm trying to create foreign keys in Laravel.我正在尝试在 Laravel 中创建外键。 However, when I migrate my table using Artisan, I get the following error.但是,当我使用 Artisan 迁移我的表时,我收到以下错误。
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
posts
add constraintposts_category_id_foreign
foreign key (category_id
) referencescategories
(id
)) Illuminate\Database\QueryException:SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter tableposts
添加约束posts_category_id_foreign
外键(category_id
)引用categories
(id
))
Posts migration帖子迁移
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');
});
Categories migration类别迁移
Schema::create('categories', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->string('slug')->unique();
$table->uuid('parent')->nullable();
});
In your posts
schema you're setting the author_id
and category_id
as null on deleting, but you didn't set those fields as nullable.在您的posts
架构中,您在删除时将author_id
和category_id
设置为 null,但您没有将这些字段设置为可为空。 Changing the definition to:将定义更改为:
$table->uuid('author_id')->nullable();
$table->uuid('category_id')->nullable();
should do it.应该这样做。
Split your foreign key declarations in to their own Schema method...将您的外键声明拆分为它们自己的 Schema 方法...
I don't understand the cause of the problem, but doing this has always worked for me.我不明白问题的原因,但这样做一直对我有用。
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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.