首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel迁移-外键SQL错误

Laravel迁移-外键SQL错误
EN

Stack Overflow用户
提问于 2018-04-12 11:41:54
回答 1查看 35关注 0票数 0

我有一个包含hazard_category_id的hazard_categories表

在我的hazard_videos表中,我想参考一下。

我的危险类别迁移如下:

代码语言:javascript
复制
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();
        });

我编写了我的迁移如下:

代码语言:javascript
复制
    Schema::table('hazard_videos', function (Blueprint $table)
    {
        $table->integer('video_category')->unsigned();
        $table->foreign('video_category')->references('hazard_category_id')->on('hazard_categories');
    });

但是当我运行这个程序时,我得到了MySQL错误:

代码语言:javascript
复制
[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错误。

是否有更好的方法来编写引用完整性约束?

EN

回答 1

Stack Overflow用户

发布于 2018-04-12 11:55:56

如果表中已经有数据,则video_category的值必须是有效的外键:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49795629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档