简体   繁体   English

Laravel - 1215无法添加外键约束

[英]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 例如: 2016_03_27_0000_first将在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. 我注意到你有“onDelete('set null')”对于你试图设置为非可空的字段。 That would also cause a problem if the role was deleted, since it would then try to set the value to null. 如果角色被删除,这也会导致问题,因为它会尝试将值设置为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 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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