首页 > 解决方案 > errno: 150 "Foreign key constraint is incorrectly formed" in Laravel migration

问题描述

I am using Laravel 5.7 version. I got the below error for users_activations table while run the command php artisan migrate

SQLSTATE[HY000]: General error: 1005 Can't create table auf.#sql-1ecc_fa (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users_activations add constraint users_activations_user_id_foreign foreign key (user_id) references users (id) on delete cascade)

users_activations table

Schema::create('users_activations', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); // got error for this line
        $table->string('token');
        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

user table

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('role_id')->default('1');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

I have already googling for the error.

I have changed

$table->integer('user_id')->unsigned();

of users_activations table with

$table->unsignedInteger('user_id');. But not worked.

Somebody help me please ?

Thanks in advance

标签: phplaravellaravel-5

解决方案


外键应与 id 类型相同,将外键更改为 bigInteger:

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

推荐阅读