首页 > 解决方案 > 添加外键时Laravel迁移错误

问题描述

所以我得到这个错误:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table yamldb#sql-3928_6ea(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table tblquestion add constraint tblquestion_que_csd_id_foreignforeign key ( que_csd_id) 引用tblcsdomain( csd_id))

表格1

Schema::create('tblquestion', function (Blueprint $table) {
    $table->increments('que_id');
    $table->string('que_name', 128);
    $table->string('que_identifier', 128);
    $table->string('que_version', 50);
    $table->char('que_content');
    $table->char('que_answers');
    $table->integer('que_grd_id')->unsigned();
    $table->integer('que_quf_id')->unsigned();
    $table->integer('que_lan_id')->unsigned();
    $table->boolean('que_mandatory', false);
    $table->char('que_thisisinformatics');
    $table->char('que_translations');
    $table->char('que_explanation');
    $table->char('que_background_info');
    $table->integer('que_cou_id')->unsigned();
    $table->boolean('que_allow_share', false);
    $table->integer('que_source_cou_id')->unsigned();
    $table->integer('que_source_que_id');
    $table->mediumInteger('que_csd_id')->unsigned();
    $table->string('que_token', 32);    
});

表 2

Schema::create('tblcsdomain', function (Blueprint $table) {
    $table->increments('csd_id');
    $table->string('csd_name', 128);
    $table->string('csd_token', 128);
 });

移民

 Schema::table('tblquestion', function (Blueprint $table) {
    $table->foreign('que_csd_id')->references('csd_id')->on('tblcsdomain');
}

此外,我正在尝试将 FK 添加到已经存在的列中。Laravel 添加了 FK,但在回滚时它不会删除它们。

Schema::table('tblquestion', function (Blueprint $table) {
    $table->dropForeign(['que_csd_id']);
}

标签: phplaravelforeign-keysmigration

解决方案


您的外键需要与主键的类型相同。

你要么需要使用

$table->mediumIncrements('csd_id');

在 id 列的表 2 迁移中。或者改变类型

$table->mediumInteger('que_csd_id')->unsigned();

$table->integer('que_csd_id')->unsigned();

推荐阅读