Adam Silva
Adam Silva

Reputation: 1047

Laravel Seeding Database

I'm using Laravel and I'm trying to seed some data into my database(phpmyadmin). I have two tables, users and carrinho. Their relationship is Users hasMany Carrinho. In the Carrinho table, I have a foreign key IDUser. I'm getting errors when I try to seed Carrinho. Here is my CarrinhoSeeder file:

<?php

class CarrinhoTableSeeder extends Seeder {

public function run()
{
    DB::table('carrinho')->delete();

    $carrinho = array(
        array(
            'IDUser' => 1,
            'estado'      => true,
        ),
        array(
            'IDUser' => 2,
            'estado'      => true,
        )
    );

    DB::table('carrinho')->insert( $carrinho );
}

}

The error I'm getting is:

[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (loj a.carrinho, CONSTRAINT carrinho_iduser_foreign FOREIGN KEY (IDUser) REFERENCES users (IDUser) ON DELETE CASCADE) (SQL: insert into carrinho (IDUser, estado) values (1, 1), (2, 1))

Does anybody know what I have wrong?

Upvotes: 0

Views: 821

Answers (2)

Md. A. Apu
Md. A. Apu

Reputation: 1250

Although @sisou 's answer is enough to solve the problem, but I thing that is not quite the way that should be followed.

Disabling foreign key checks is not a good idea. This will hamper data integrity & may cause problems in future,

Just make sure that you've users with those ID's (that you're referencing in carrinho table).

Your error clearly pointing that you don't have those users in users table.

Hope by adding users with those ID's will solve your problem.

Btw, you column naming is also not in compliance with Laravel convention. Laravel will be expection user_id by default but u'r using IDUser. This will cause problem. So you've to poing that in your relationship. If you have blur lines in Laravel relationships then you can check the docs here

Upvotes: 0

sisou
sisou

Reputation: 323

You need to make sure that the users with the referenced IDs (1 & 2) already exist in the database. If it still doesn't work, you can temporarily disable foreign key checks with the following:

DB::statement('SET FOREIGN_KEY_CHECKS=0;');

DB::table('carrinho')->insert( $carrinho );

DB::statement('SET FOREIGN_KEY_CHECKS=1;');

Upvotes: 2

Related Questions