Reputation: 2454
I'm on Laravel 5.8 on a XAMPP stack.
Consider these two migrations to create two tables:
post_categories table.
Schema::create('post_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->string('status');
$table->timestamps();
});
posts table.
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->mediumText('description');
$table->integer('views');
$table->integer('post_category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('post_category_id')->references('id')->on('post_categories');
});
When I run php artisan migrate
, I'm getting the following error:
General error: 1005 Can't create table
testdb
.#sql-38d8_102
(errno: 150 "Foreign key constraint is incorrectly formed").
I've tried running both:
php artisan migrate
php artisan migrate:fresh
I also tried changing the post_category_id
field to a regular integer, instead of unsigned: no difference.
Also restarted the MySQL server and Apache service, didn't make a difference.
The post_categories
migration runs before the posts
migration. The posts
table gets created, but the foreign key doesn't.
Why is this error being thrown and how do I solve it?
Upvotes: 4
Views: 5582
Reputation: 85
I had the same error where I wanted to link two tables, users tables and deposits tables. I tried many options but they didn't work. However, this is what worked for me on create deposits migration:
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Upvotes: 0
Reputation: 134
Instead of this:
$table->integer('post_category_id')->unsigned();
Try this:
$table->unsignedBigInteger('post_category_id');
Upvotes: 0
Reputation: 644
This might be happening because you're trying to create a foreign key with an integer field to a big integer field. In your posts migration, instead of this
$table->integer('post_category_id')->unsigned();
do this:
$table->bigInteger('post_category_id')->unsigned();
Upvotes: 11