我有一个包含hazard_category_id的hazard_categories表
在我的hazard_videos表中,我想参考一下。
我的危险类别迁移如下:
Schema::create('hazard_categories', function (Blueprint $table) {
$table->increments('hazard_category_id');
$table->string('hazard_category_name');
$table->string('hazard_category_thumb');
$table->integer('hazard_category_total');
$table->timestamps();
$table->softDeletes();
});我编写了我的迁移如下:
Schema::table('hazard_videos', function (Blueprint $table)
{
$table->integer('video_category')->unsigned();
$table->foreign('video_category')->references('hazard_category_id')->on('hazard_categories');
});但是当我运行这个程序时,我得到了MySQL错误:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`icourse`.`#sql-da4_40df`, CONSTRAINT `hazard_videos_video_category_foreign` FOREIGN KEY (`video_category`) REFERENCES `hazard_categorie
s` (`hazard_category_id`)) (SQL: alter table `hazard_videos` add constraint `hazard_videos_video_category_foreign` foreign key (`video_category`) references `hazard_categories` (`hazard_category_id`))我为什么要拿到这个?我已经镜像了Laravel文档,但是遇到了一个MySQL错误。
是否有更好的方法来编写引用完整性约束?
发布于 2018-04-12 11:55:56
如果表中已经有数据,则video_category的值必须是有效的外键:
Schema::table('hazard_videos', function (Blueprint $table) {
$table->integer('video_category')->unsigned();
});
HazardVideo::query()->update(['video_category' => 1]);
Schema::table('hazard_videos', function (Blueprint $table) {
$table->foreign('video_category')->references('hazard_category_id')
->on('hazard_categories');
});或者将列设置为nullable。
https://stackoverflow.com/questions/49795629
复制相似问题