errno:150“迁移键laravel 6中错误地形成了外键约束

时间:2020-03-07 13:58:54

标签: php laravel migration

我是laravel的新手,对不起,我的英语不好。我已经制作了迁移文件并运行了

  1. create_colleges_table.php

公共功能up() {

 Schema::create('colleges', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->char('nim', 10);
        $table->string('email');
        $table->integer('major_id');
        $table->timestamps();
    });
}
  1. create_majors_table.php

公共功能up() {

Schema::create('majors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('major_name');
        $table->timestamps();
    });
}

然后我制作update_colleges_table.php,运行它并得到如下错误:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `learn_laravel_crud`.`#sql-1558_e3` (errno:
150 "Foreign key constraint is incorrectly formed") (SQL: alter table `colleges` add constraint `colleges_major_id_foreign` foreign key (`major_id`) references `majors` (`id`))

这是我在update_colleges_table.php中的代码

公共功能up()

{
    Schema::table('colleges', function (Blueprint $table){
        $table->foreign('major_id')->references('id')->on('majors');
    });

}

1 个答案:

答案 0 :(得分:1)

要创建Foreign keychild column的数据类型必须与parent column完全匹配。

由于majors.idbigIncrements,即unsigned big integer,所以colleges.major_id也需要是bigInteger,而不是integer

因此更改

 $table->integer('major_id');

$table->unsignedBigInteger('major_id');