-1

I have the following two migration files:

Schema::create('words', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->integer('book_id')->unsigned()->nullable();
    $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
    $table->string('title');
    $table->longText('definition', 2056);
    $table->timestamps();
});

and:

Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->integer('word_id')->unsigned()->nullable();
    $table->foreign('word_id')->references('book_id')->on('words');
    $table->string('title');
    $table->string('author')->nullable();
    $table->date('start_date')->nullable();
    $table->date('end_date')->nullable();
    $table->integer('no_pages')->nullable();
    $table->integer('current_page')->nullable();
    $table->integer('status')->nullable();
    $table->timestamps();
});

When I run the migrate command, the following error occur:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Ca
n't create table `words`.`#sql-16bc_76` (errno: 150 "Foreign key constraint is i
ncorrectly formed") (SQL: alter table `books` add constraint `books_word_id_fore
ign` foreign key (`word_id`) references `words` (`book_id`))

Why is this happens? I've added word_id into books table so I can count the words added for that book.

zlatan
  • 3,346
  • 2
  • 17
  • 35
Cicharito
  • 131
  • 5
  • 17
  • 1
    Possible duplicate of [Laravel migration can't create foreign key](https://stackoverflow.com/questions/56395229/laravel-migration-cant-create-foreign-key) – Salman Zafar Jun 20 '19 at 09:03
  • you can not create a foreign key to a column in a table that does not yet exist. you would have to choose if `words` will have a foreign key to `books` or if `books` will have a foreign key to `words`. then run the migrations in the correct order – porloscerros Ψ Jun 20 '19 at 09:05

1 Answers1

0

The problem could be that the tables that contain the id that is being used as a foreign id needs to be created before another table can reference it. Basically, you are creating a table and telling MySQL to reference another table's primary key but that table doesn't exist yet. Try to create them separately.

zlatan
  • 3,346
  • 2
  • 17
  • 35