Warm tip: This article is reproduced from stackoverflow.com, please click
laravel mysql php

LARAVEL:MYSQL : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key

发布于 2020-03-27 10:28:56

I am trying to apply a foreign Key to column user_id, related with ID of table users

I have tried doing it by migrations and in workbench and this error keeps coming:

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

this is the mysql:

ALTER TABLE `dh_booky`.`books` 

ADD CONSTRAINT `books_user_id_foreign`

  FOREIGN KEY (`user_id`)

  REFERENCES `dh_booky`.`users` (`id`)

  ON DELETE NO ACTION

  ON UPDATE NO ACTION;

1st migration books:

 public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('title_id')->unsigned();
            $table->foreign('title_id')->references('id')->on('titles');
            $table->bigInteger('author_id')->unsigned();
            $table->foreign('author_id')->references('id')->on('authors');
            $table->string('image')->nullable();

        });
    }

Update migration books:

class UpdateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        //php artisan make:migration update_votes_table



});

User migration:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
        });
    }
Questioner
petrushka_95
Viewed
399
Watercayman 2019-07-03 23:42

Set the user migration to earlier, before the books table migration happens. Otherwise, there is no user table in existence yet to reference when creating the books table, and thus the error.

This one first:

Schema::create('users', function (Blueprint $table) {...}

Then when you create the books table, the foreign key to users will have a table to connect to.