【问题标题】:Laravel Migration - Foreign Key SQL ErrorLaravel 迁移 - 外键 SQL 错误
【发布时间】: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中是否已有数据?

标签: mysql laravel migration


【解决方案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

【讨论】:

  • 太好了,谢谢@Jonas
猜你喜欢
  • 2019-01-31
  • 2014-09-27
  • 2016-07-06
  • 2015-08-14
  • 2015-03-02
  • 2019-02-09
  • 2016-02-10
  • 2020-01-16
  • 2019-10-19
相关资源
最近更新 更多