Why is creating Foreign Key in Laravel 5.8 failing?

点点圈 提交于 2019-12-28 23:05:21

问题


The migration script below was running smoothly in an older version of Laravel but I added it to my fresh Laravel 5.8 and ran the script. I'm getting Error: foreign key was not formed correctly

Evaluation Migration:

public function up() { 
    Schema::create('evaluation', function (Blueprint $table) { 
        $table->increments('id'); 
        $table->integer('user_id')->unsigned()->index(); 
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Users Migration:

public function up() { 
    Schema::create('users', function (Blueprint $table) { 
        $table->bigIncrements('id'); 
        $table->timestamps();
    });
}

回答1:


As we discussed in the comments above, a foreign key column must be the same data type as the primary key it references.

You declared your user.id primary key as $table->bigIncrements('id') which becomes BIGINT UNSIGNED AUTO_INCREMENT in MySQL syntax.

You must declare the foreign key as $table->unsignedBigInteger('user_id') which will become BIGINT UNSIGNED in MySQL, making it compatible with being a foreign key to the user.id column.




回答2:


  update your `integer('user_id')` to `bigInteger('user_id')`
public function up() { 
        Schema::create('evaluation', function (Blueprint $table) { 
            $table->increments('id'); 
            $table->bigInteger('user_id')->unsigned()->index(); 
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }


来源:https://stackoverflow.com/questions/54990828/why-is-creating-foreign-key-in-laravel-5-8-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!