php - (Laravel) 错误号 : 150 "Foreign key constraint is incorrectly formed

标签 php mysql laravel laravel-5

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

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 表的外键创建 users 表时,roles 表不存在但是,因此您无法添加引用它的外键。

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

如果您绝对确定 roles 表需要 users 表的外键,那么您需要从 users 中删除外键创建 表定义,并在创建 roles 表后将其作为 alter table 单独添加回来。

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

关于php - (Laravel) 错误号 : 150 "Foreign key constraint is incorrectly formed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101878/

相关文章:

php - 如何使用 SUM(CASE) 和日期间隔来选择用户及其金额列表和总金额

php - 使用php访问远程数据库

php - 使用 PHP 将图像添加到 excel 文件

php - 从表中选择,其中 a 列不等于 b 列(在同一个表上)且 tableID = 2

php - Laravel 加入查询

mysql - Laravel数据库结构 'apply'

php - 取消设置数组值(将对象转换为数组后)

mysql - mysql中总和总是返回1

MySQL函数从多个表中添加价格

laravel - Eloquent WHERE AND "sub"OR