Reputation: 87
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();
});
Upvotes: 0
Views: 383
Reputation: 1297
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.
Upvotes: 2
Reputation: 1019
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');
});
Upvotes: 1