laravel - 外键约束格式不正确(Laravel 迁移)
问题描述
如错误日志中所写,可能错误是由于引用表和父表中的不同形式引起的,但我仍然不明白,因为我是编程新手
这里表1
<?php
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('question');
$table->unsignedInteger('quiz_id');
$table->timestamps();
});
这里表2
<?php
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('question_id');
$table->string('answer');
$table->boolean('is_correct');
$table->timestamps();
});
Schema::table('answers', function (Blueprint $table){
$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
});
我应该在这段代码中改变什么?谢谢
解决方案
从Laravel 5.8 $table->id()
开始,它是一个别名,$table->bigIncrements('id')
它在后台将id
列的数据类型设置为无符号BIGINT
。
在answers
表格中,您拥有$table->unsignedInteger('question_id');
相当于 unsigned INT
/数据类型并且与表格中表示的INTEGER
内容不兼容的类型。所以你必须在表中将列的数据类型更改为无符号。$table->id()
questions
question_id
BIGINT
answers
为此,您需要使用Blueprint::unsignedBigInteger()
方法将question_id
列的数据类型设置为无符号BIGINT
,因为您将其设置为外键。
所以使用
$table->unsignedBigInteger('question_id');
代替
$table->unsignedInteger('question_id');
推荐阅读
- python - 如何在请求中访问烧瓶属性
- alamofire - 错误域 = NSPOSIXErrorDomain 代码 = 28 “设备上没有剩余空间” UserInfo = {_kCFStreamErrorCodeKey = 28,_kCFStreamErrorDomainKey = 1}
- sql - 从多列中选择数据
- javascript - TypeError:无法在反应js中读取null的属性'push'
- javascript - 垂直不对齐 div
- reactjs - 当我 create-react-app 说我的 create-react-app 已过时但我无法更新或卸载它时,我的终端向我抛出错误
- swift - Swift 和 Firebase:用户类型的值没有成员 asDict()
- c# - 是否可以为 Action DropDown 设置默认值?
- flutter - 颤振类型'列表
' 不是类型 'List 的子类型 ' - servicestack - 在 Unity 中使用 SharpScript