外键在Laravel中错误地形成

时间:2019-06-20 08:49:50

标签: laravel migration constraints integrity

我有以下两个迁移文件:

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();
});

和:

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();
});

当我运行migration命令时,会发生以下错误:

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`))

为什么会这样?我已经在图书表中添加了word_id,以便可以计算为该书添加的单词。

1 个答案:

答案 0 :(得分:0)

问题可能是在另一个表可以引用它之前,需要创建包含被用作外部ID的ID的表。基本上,您正在创建一个表并告诉MySQL引用另一个表的主键,但该表尚不存在。尝试分别创建它们。