简体   繁体   中英

Laravel - 1215 Cannot add foreign key constraint

I try to add a foreign key constraint in migrations. For some reason it does work when I set it to nullable, but it doesn't work when I make it not nullable. Why does this happen and how can I solve this?

This does work:

Schema::create('role_user', function (Blueprint $table){
        $table->increments('id');

        $table->integer('role_id')->unsigned()->index()->nullable();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('set null');

        $table->integer('user_id')->unsigned()->index()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');

         $table->timestamps();
    });

This throws the exception:

Schema::create('role_user', function (Blueprint $table){
        $table->increments('id');

        $table->integer('role_id')->unsigned()->index();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('set null');

        $table->integer('user_id')->unsigned()->index()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');

         $table->timestamps();
    });

Both the role and user tables already excist before making these constraints. I want them to be not nullable (so they must be filled). The error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete set null)

The migrations happen in the order that you specify in the filename. Maybe your roles table hasn't been created by the time this migration is run and your DB complains about trying to reference a field in a (yet) non-existent table?

For example: 2016_03_27_0000_first will be executed before 2016_03_28_0000_second

UPDATE: Added solution.

I noticed that you have "onDelete('set null')" for the field that you are trying to set as non-nullable. That would also cause a problem if the role was deleted, since it would then try to set the value to null.

You should set both foreign keys to:

->onDelete('cascade')

This way if the user or the role get deleted, any associations related to them would also get deleted automatically and not simply set to null or left hanging around.

Cheers

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