I'm trying to create foreign keys in Laravel. However, when I migrate my table using Artisan, I get the following error.
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
))
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. 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...
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');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.