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条)

报告相同问题?