外键约束格式错误(Laravel迁移)

时间:2020-07-02 15:42:43

标签: laravel migration laravel-migrations

如错误日志中所写,可能是由于错误导致了引用表和父表的形式不同,但我仍然不明白,因为我是编程新手。

此处是表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');
});

该代码应更改什么?谢谢

3 个答案:

答案 0 :(得分:3)

Laravel 5.8开始,$table->id()$table->bigIncrements('id')的别名,它在后台将id列的数据类型设置为无符号BIGINT

answers表中,您拥有$table->unsignedInteger('question_id');,它等效于无符号的INT / INTEGER数据类型,并且与$table->id()的数据类型不兼容代表questions表中。因此,您必须将question_id表中的BIGINT列的数据类型更改为未签名的answers

为此,您需要使用Blueprint::unsignedBigInteger()方法来将question_id列的数据类型设置为外键BIGINT,将其设置为外键。

因此使用

$table->unsignedBigInteger('question_id'); 

代替

$table->unsignedInteger('question_id'); 

答案 1 :(得分:1)

当心:Laravel 5.8为外键添加了bigInteger(作为默认值)

在外键列中执行bigInteger()而不是integer()

$table->unsignedBigInteger('question_id');

答案 2 :(得分:1)

$table->id();$table->bigIncrements('id')的别名,因此您应该使用$table->unsignedBigInteger('question_id');