【发布时间】:2019-07-26 05:07:11
【问题描述】:
下面的迁移脚本在旧版本的 Laravel 中运行顺利,但我将它添加到我的新 Laravel 5.8 并运行脚本。我收到Error: foreign key was not formed correctly
评估迁移:
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');
});
}
用户迁移:
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
});
}
【问题讨论】:
-
users表在您运行之前是否存在?您不能在表存在之前声明外键引用它。 -
我不是 laravel 专家,但看起来
users.id将成为BIGINT但您将evaluation.user_id声明为INT UNSIGNED?那是行不通的。它们必须是完全相同的数据类型。 -
啊哈,我找到了blog,它确认 Laravel 增量类型默认是无符号的。但是您应该将外键列声明为
bigInteger以匹配它引用的主键的大小。 -
我也不确定在 Laravel 语法中
bigIncrements是否隐式声明user.id作为该表的主键?外键应引用作为主键或唯一键的列。 -
@BillKarwin 我将迁移代码中的
user_id更改为$table->unsignedBigInteger('user_id');现在可以正常工作了。