作者:ririye2011 | 来源:互联网 | 2023-02-05 13:24
我试图创建一个外键使用artisan
,但这个错误出现了.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_comment_lot_id_foreign` foreign key (`comment_lot_id`) references `lots` (`lot_id`
) on delete cascade)
这是我的迁移:
increments('id');
$table->text('comment');
$table->integer('comment_lot_id')->unsigned();
$table->timestamps();
});
Schema::table('comments', function ($table) {
$table->foreign('comment_lot_id')->references('lot_id')->on('lots')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropForeign(['comment_lot_id']);
Schema::dropIfExists('comments');
}
}
在批次表我用 它lot_id
作为id
模型Lot.php我添加:
知道如何解决这个错误?
1> korwalskiy..:
将以下规则应用于迁移文件:
[1]
父,数据透视表必须基于支持外键引用的引擎(例如InnoDB for mysql).
$table->engine = “InnoDB”;
在其他列定义之前,在迁移文件中执行.
我观察laravel始终默认为MyISAM,因此这条线是必须的.
[2]
父级中引用的列必须是主键或唯一键.
父表中的这些声明很好:
$table->increments(“id”);
表示列"id"是可引用的
$table->column_type(“column_name”)->unique();
表示列"column_name"是可引用的
[3]
数据透视表列的类型必须与其引用的父表列的类型相同.
因此,例如,应引用增量("id")的数据透视表列必须是unsignedInteger类型.
如果父表是char(20)类型,那么用于引用它的数据透视表列也必须是char(20)类型.
完成上述所有三项操作后,请根据需要定义外键关系.
谢谢 !它奏效了.'$ table-> engine ='MyISAM'; '因为父表也是MyISAM 2. $ table-> integer('comment_lot_id') - > unique() - > unsigned(); 很多父表
2> 小智..:
看来这对您来说不是问题,但我在Laravel 5.8中遇到了相同的错误,并发现了一个有趣的问题:Laravel现在将'id'列默认为'bigIncrements',而不仅仅是'increments'。因此,您不必像以前那样使用“整数”来引用它,而必须使用“ bigInteger”来引用它。
如果您的父表如下所示:
$table->bigIncrements('id');
然后,子迁移需要如下所示:
$table->bigInteger('parent_id')->unsigned()->index();
$table->foreign('parent_id')->references('id')->on('parent');
希望这可以帮助其他在5.8及更高版本中遇到此问题的人。