外键约束的格式不正确,Laravel
Foreign key constraint is incorrectly formed, Laravel
我尝试迁移数据库,但出现错误,我不确定原因。不确定 "incorrectly formed".
是什么
//First Table
Schema::create('lkp_anime_lists', function (Blueprint $table) {
$table->id();
//more columns here
});
//Second one
Schema::create('lkp_cards', function (Blueprint $table) {
$table->id();
$table->integer('lkp_anime_list_id');
});
Schema::table('lkp_cards', function ($table) {
$table->foreign('lkp_anime_list_id')
->references('id')
->on('lkp_anime_lists')
->onDelete('cascade');
});
SQLSTATE[HY000]: General error: 1005 Can't create table anime_db
.lkp_cards
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table lkp_cards
add constraint lkp_cards_lkp_anime_list_id_foreign
foreign key (lkp_anime_list_id
) references lkp_anime_lists
(id
) on delete cascade)
你应该使用
$table->unsignedBigInteger('lkp_anime_list_id')
而不是因为主键和外键应该是相同的数据类型
这对我有用
$table->bigInteger('lkp_anime_list_id')->unsigned();
对于 Laravel 版本 6+
我尝试迁移数据库,但出现错误,我不确定原因。不确定 "incorrectly formed".
是什么//First Table
Schema::create('lkp_anime_lists', function (Blueprint $table) {
$table->id();
//more columns here
});
//Second one
Schema::create('lkp_cards', function (Blueprint $table) {
$table->id();
$table->integer('lkp_anime_list_id');
});
Schema::table('lkp_cards', function ($table) {
$table->foreign('lkp_anime_list_id')
->references('id')
->on('lkp_anime_lists')
->onDelete('cascade');
});
SQLSTATE[HY000]: General error: 1005 Can't create table
anime_db
.lkp_cards
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tablelkp_cards
add constraintlkp_cards_lkp_anime_list_id_foreign
foreign key (lkp_anime_list_id
) referenceslkp_anime_lists
(id
) on delete cascade)
你应该使用
$table->unsignedBigInteger('lkp_anime_list_id')
而不是因为主键和外键应该是相同的数据类型
这对我有用
$table->bigInteger('lkp_anime_list_id')->unsigned();
对于 Laravel 版本 6+