简体   繁体   中英

1215 Cannot add foreign key constraint in laravel

Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->integer('age')->unsigned();
        $table->integer('city_id')->unsigned();
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
        $table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->timestamps();
});

i'm new laravel, when i run migrate, in terminal show

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table students add constraint students_city_id_foreign foreign key ( city_id ) references cities ( id ) on delete cascade)

help me fix

Your problem is on the order of the code. You want to make a foreign key to a table which is not yet exists.

Try this instead:

Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->integer('age')->unsigned();
        $table->integer('city_id')->unsigned();
        $table->timestamps();
});

Schema::create('cities', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->timestamps();
});

Schema::table('students', function(Blueprint $table) {
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
    });

Like this, you first creates both tables, and after that you set the foreign key.

If you are using more recent version of Laravel id fields are now unsignedBigInteger field. So you should do something like:

Schema::create('cities', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->integer('age')->unsigned();
        $table->foreignId('city_id')->constrained()->onDelete('cascade');
        $table->timestamps();
});

Also, make sure the cities migration is running before students.

=>your cities migration first create then after students migration create because your city_id foreign key reference to the cities table laravel migration check order and order wise migration run so first cities migration run(cities table create) then students migration run.

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