简体   繁体   中英

Problem with add a foreign key to same table in Laravel - Error : “Cannot add foreign key constraint”

I have a table "users". Some users are linked to other users via the "consultant_id" field.

When I create my database with php artisan migrate , I receive an error 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');
        });

Can you help me ?

Thank you very much!

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

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

Your user table's primary key is a big integer , the foreign key field you are trying to use is a normal integer .

Try:

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

Try this

 Schema::disableForeignKeyConstraints();

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

Schema::enableForeignKeyConstraints();

You should try this:

Change following line

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

TO

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

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