在Laravel中向同一表添加外键的问题-错误:“无法添加外键约束”

时间:2019-07-11 07:13:23

标签: php mysql laravel

我有一个“用户”表。某些用户通过“ consultant_id”字段链接到其他用户。

使用php artisan migrate创建数据库时,收到错误PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name', 255);
            $table->string('last_name', 255);
            $table->string('email', 255)->unique();
            $table->string('password');
            $table->integer('consultant_id')->unsigned()->nullable()->index();
            $table->integer('profile_id')->unsigned()->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
Schema::table('users', function(Blueprint $table) {
            $table->foreign('consultant_id')->references('id')->on('users')
                        ->onDelete('set null')
                        ->onUpdate('cascade');
        });

你能帮我吗?

非常感谢您!

4 个答案:

答案 0 :(得分:0)

您的用户表的primary keybig integer,您要使用的外键字段是普通的integer

尝试:

$table->bigInteger('consultant_id')->unsigned()->nullable()->index();

答案 1 :(得分:0)

尝试一下

 Schema::disableForeignKeyConstraints();

 Schema::table('users', function(Blueprint $table) {
        $table->foreign('consultant_id')->references('id')->on('users')
                    ->onDelete('set null')
                    ->onUpdate('cascade');
 });

Schema::enableForeignKeyConstraints();

答案 2 :(得分:0)

尝试将此代码放在down方法中

Schema::dropForeign(['consultant_id']);

答案 3 :(得分:-1)

您应该尝试以下操作:

更改下一行

$table->integer('consultant_id')->unsigned()->nullable()->index();

$table->bigInteger('consultant_id')->unsigned();
相关问题