【发布时间】:2018-09-22 13:15:16
【问题描述】:
我有一个 hazard_categories 表,其中包含一个 hazard_category_id
我想在我的 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 错误。
有没有更好的方法来编写我的参照完整性约束?
【问题讨论】:
-
检查迁移顺序
-
请添加
hazard_categories的迁移。 -
你在两个表中都使用 InnoDB 引擎吗?
-
当然,会修改问题...
-
hazard_videos中是否已有数据?