首页 > 解决方案 > 外键约束格式不正确(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');
});

我应该在这段代码中改变什么?谢谢

标签: laravelmigrationlaravel-migrations

解决方案


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

answers表格中,您拥有$table->unsignedInteger('question_id');相当于 unsigned INT/数据类型并且与表格中表示的INTEGER内容不兼容的类型。所以你必须在表中将列的数据类型更改为无符号。$table->id()questionsquestion_idBIGINTanswers

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

所以使用

$table->unsignedBigInteger('question_id'); 

代替

$table->unsignedInteger('question_id'); 

推荐阅读