Why is creating Foreign Key in Laravel 5.8 failing?(为什么在 Laravel 5.8 中创建外键失败?)
问题描述
下面的迁移脚本在旧版本的 Laravel 中运行流畅,但我将它添加到我的新 Laravel 5.8 中并运行了脚本.我收到错误:外键未正确形成
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
评估迁移:
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();
});
}
推荐答案
正如我们在上面的评论中所讨论的,外键列必须与它引用的主键具有相同的数据类型.
As we discussed in the comments above, a foreign key column must be the same data type as the primary key it references.
您将您的 user.id 主键声明为 $table->bigIncrements('id'),它变成了 BIGINT UNSIGNED AUTO_INCREMENTMySQL 语法.
You declared your user.id primary key as $table->bigIncrements('id') which becomes BIGINT UNSIGNED AUTO_INCREMENT in MySQL syntax.
您必须将外键声明为 $table->unsignedBigInteger('user_id') 这将在 MySQL 中变为 BIGINT UNSIGNED,使其与作为外键兼容user.id 列的键.
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.
这篇关于为什么在 Laravel 5.8 中创建外键失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 Laravel 5.8 中创建外键失败?
基础教程推荐
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
