我是laravel的新手,对不起,我的英语不好。我已经制作了迁移文件并运行了
公共功能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();
});
}
公共功能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');
});
}
答案 0 :(得分:1)
要创建Foreign key
,child column
的数据类型必须与parent column
完全匹配。
由于majors.id
是bigIncrements
,即unsigned big integer
,所以colleges.major_id
也需要是bigInteger
,而不是integer
。
因此更改
$table->integer('major_id');
至
$table->unsignedBigInteger('major_id');