duanlaofu4108 2017-11-04 16:40
浏览 86
已采纳

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行(laravel5)

at first, I'm sorry for poor english.

I have created tables in MariaDB(innoDB, laravel5) as shown below :

*user table

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

*article table

    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->index();
        $table->string('title');
        $table->text('content');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
    });

*tags table

    Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('slug')->index();
        $table->timestamps();
    });

*article_tag table

   Schema::create('article_tag', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('article_id')->unsigned();
        $table->integer('tag_id')->unsigned();

        $table->foreign('article_id')->references('id')->
        on('articles')->onDelete('cascade');
        $table->foreign('tag_id')->references('id')->
        on('tags')->onDelete('cascade');
    });

so when I try to insert values into article_tag table i get:

insert into `article_tag` (`article_id`, `tag_id`) values (3, 9);

*error message

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mmdance`.`article_tag`, CONSTRAINT `article_tag_tag_id_foreign` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE) (SQL: insert into `article_tag` (`article_id`, `tag_id`) values (1, 9))

I've seen the other posts on this topic, but didn't solution.
thanks for your help. thanks.

  • 写回答

2条回答 默认 最新

  • dpgkg42484 2017-11-04 20:01
    关注

    Simply import the Schema facade where you are creating/updating a record.

    \Schema::disableForeignKeyConstraints();
    // Your query
    \Schema::enableForeignKeyConstraints(); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 xshell无法连接提示ssh服务器拒绝密码
  • ¥15 AT89C52单片机C语言关于串口通信的位操作
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?