(Laravel) errno: 150 "外键约束的格式不正确

(Laravel) errno: 150 "Foreign key constraint is incorrectly formed

我尝试迁移我的表,但它显示错误:

errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_role_id_foreign foreign key (role_id) references roles (id))

这是我的表:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('fullname');
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('password');
        $table->integer('role_id')->unsigned();
        $table->foreign('role_id')->references('id')->on('roles');
        $table->rememberToken();
        $table->timestamps();
    });


Schema::create('roles', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name')->unique();
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->timestamps();
    });


Schema::create('posts', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('content');
        $table->string('image');
        $table->timestamps();
    });

问题是,当您使用 roles table 的外键创建 users table 时,那么 roles table 尚不存在,因此您无法添加引用它的外键。

我还注意到 roles table 也有一个引用 users table 的外键,这使得情况更加棘手。

如果您完全确定 roles table 需要 users table 的外键,那么您需要从users table 定义,在 roles table 创建后单独添加回 alter table

但是,我不确定 roles table 是否应该具有 users table 的 fk(除非它代表创建该角色的用户) 因为您可以在一个角色中拥有多个用户。如果您正在为多对多关系建模,那么这不是实现它的方法。但这与当前错误无关,因此仅将其视为旁注。

有时,由于迁移顺序,也会发生该错误。如果你遇到 errno 150 "Foreign key constraint is incorrectly formed" 然后转到你的迁移文件夹并检查父 table 迁移是否首先执行。如果childtable迁移按照迁移顺序先执行,会尝试查找外键绑定,报错