1452 Cannot add or update a child row: a foreign key constraint fails - but id of user exist

Viewed 63

I have three table ; users , products and transactions the id fields is auto increment in laravel.

products :

Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('title')->nullable();
        $table->unsignedBigInteger('user_id')->index();
        $table->integer('price')->nullable();
        $table->text('description')->nullable();
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

transactions :

Schema::create('transactions', function (Blueprint $table) {
        $table->id()->from('1000');
        $table->unsignedBigInteger('user_id');
        $table->integer('code')->nullable();
        $table->string('token')->nullable();
        $table->bigInteger('amount');
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users');
    });

users :

  Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->bigInteger('phone');
        $table->timestamp('last_seen')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });

when I insert new row on products or transactions it give me this error :

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (sabbabecom_DB.products, CONSTRAINT products_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)

insert into products (user_id, updated_at, created_at) values (2, 2022-06-25 09:38:52, 2022-06-25 09:38:52)

or :

insert into transactions (user_id, amount, updated_at, created_at) values (2, 56000, 2022-06-25 09:50:14, 2022-06-25 09:50:14)

But in the users table , a user with id 2 is exist !!!

what is wrong in my database?

thanks

0 Answers
Related