简体   繁体   中英

Cannot add foreign key constraint

    Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->text('body');
                $table->string('image')->nullable();
                $table->integer('user_id')->unsigned();
                $table->integer('category_id');
                $table->timestamps();

                $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            });

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();    
        });

----> SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table posts add constraint posts_category_id_foreign foreign key ( category_id ) references categories ( id ) on delete cascade)

Categories needs to exist before the foreign key is created, as you can not foreign key to a table that does not exists yet.

Schema::create('categories', function (Blueprint $table) {
    ...
});

Schema::create('posts', function (Blueprint $table) {
    ...
});

Secondly when you do a foreign key, you will have to have the id as the same type as the tables foreign key. When you do increments('id') it will actually create an unsigned integer, therefor your category_id in posts should be an unsigned integer.

Schema::create('posts', function (Blueprint $table) {
    $table->unsignedInteger('category_id');

    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM