外键约束的格式不正确(Laravel 迁移)
Foreign key constraint is incorrectly formed (Laravel Migration)
正如错误日志中所写,错误可能是由于引用 table 和父 table 中的不同形式引起的,但我仍然不明白,因为我是编程新手
此处table1
<?php
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('question');
$table->unsignedInteger('quiz_id');
$table->timestamps();
});
此处table 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');
});
我应该在此代码中更改什么?谢谢
As of Laravel 5.8 $table->id()
是 $table->bigIncrements('id')
的别名,它在后台将 id
列的数据类型设置为无符号 BIGINT
。
在 answers
table 中,你有 $table->unsignedInteger('question_id');
等同于无符号 INT
/INTEGER
数据类型并且与$table->id()
在 questions
table 中代表什么。所以你必须在 answers
table.
中将 question_id
列的数据类型更改为无符号 BIGINT
为此,您需要使用 Blueprint::unsignedBigInteger()
方法将 question_id
列的数据类型设置为无符号 BIGINT
,因为您将其设置为外键。
所以用
$table->unsignedBigInteger('question_id');
而不是
$table->unsignedInteger('question_id');
Be Careful: Laravel 5.8 Added bigInteger for foreign key ( As Defaults)
在您的外键列中执行 bigInteger()
而不是 integer()
。
$table->unsignedBigInteger('question_id');
$table->id();
是 $table->bigIncrements('id')
的别名,所以你应该使用 $table->unsignedBigInteger('question_id');
正如错误日志中所写,错误可能是由于引用 table 和父 table 中的不同形式引起的,但我仍然不明白,因为我是编程新手
此处table1
<?php
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('question');
$table->unsignedInteger('quiz_id');
$table->timestamps();
});
此处table 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');
});
我应该在此代码中更改什么?谢谢
As of Laravel 5.8 $table->id()
是 $table->bigIncrements('id')
的别名,它在后台将 id
列的数据类型设置为无符号 BIGINT
。
在 answers
table 中,你有 $table->unsignedInteger('question_id');
等同于无符号 INT
/INTEGER
数据类型并且与$table->id()
在 questions
table 中代表什么。所以你必须在 answers
table.
question_id
列的数据类型更改为无符号 BIGINT
为此,您需要使用 Blueprint::unsignedBigInteger()
方法将 question_id
列的数据类型设置为无符号 BIGINT
,因为您将其设置为外键。
所以用
$table->unsignedBigInteger('question_id');
而不是
$table->unsignedInteger('question_id');
Be Careful: Laravel 5.8 Added bigInteger for foreign key ( As Defaults)
在您的外键列中执行 bigInteger()
而不是 integer()
。
$table->unsignedBigInteger('question_id');
$table->id();
是 $table->bigIncrements('id')
的别名,所以你应该使用 $table->unsignedBigInteger('question_id');