【问题标题】:Foreign key constraint is incorrectly formed (Laravel Migration) [duplicate]外键约束格式不正确(Laravel Migration)[重复]
【发布时间】:2020-10-23 06:40:03
【问题描述】:

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

这里是表 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 migration laravel-migrations


    【解决方案1】:

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

    answers 表中,您有$table-&gt;unsignedInteger('question_id');,它等效于无符号INT/INTEGER 数据类型,并且与$table-&gt;id()questions 表中表示的内容不兼容。所以你必须将answers表中question_id列的数据类型改为无符号BIGINT

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

    所以用

    $table->unsignedBigInteger('question_id'); 
    

    代替

    $table->unsignedInteger('question_id'); 
    

    【讨论】:

    • @FebriTahta 不要忘记在此处标记对您有帮助的正确答案。 :)
    • 是的先生.. 感谢您的回答,我之前的命令中有错字,我已删除。我已经将此答案标记为正确。 :) 谢谢你
    【解决方案2】:

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

    在您的外键列中使用bigInteger() 而不是integer()

    $table->unsignedBigInteger('question_id');
    

    【讨论】:

    • 谢谢先生,我现在明白了:)
    【解决方案3】:

    $table-&gt;id();$table-&gt;bigIncrements('id') 的别名,所以你应该使用$table-&gt;unsignedBigInteger('question_id');

    【讨论】:

    • 感谢您的回答先生
    猜你喜欢
    • 2017-10-03
    • 2019-07-25
    • 2017-10-04
    • 2018-02-19
    • 2021-05-26
    • 2017-04-13
    • 2019-09-17
    • 2020-09-24
    • 2019-11-02
    相关资源
    最近更新 更多