Laravel Migration - 外键SQL错误

时间:2018-04-12 11:41:54

标签: mysql laravel migration

我有一个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错误。

有没有更好的方法来编写我的参照完整性约束?

1 个答案:

答案 0 :(得分:1)

如果您的表中已有数据,则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