2 votes

LARAVEL 5.2 -- Integrity constraint violation: 1452 Cannot add or update a child row: -- Problema relacionar tablas

I am trying to fill some tables with the faker library, so far I have not had any problem, since they were miniprojects and the tables were not related, but now, I'm starting with the relationships in laravel and I get an error that I can not solve.

There are three tables, book users, and categories

This is the mistake:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails (`laraveleloquentbasico`.`libros`, CONSTRAINT `libros_id_categoria_foreign` FOREIGN KEY (`id_categoria`) R
EFERENCES `categoria` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: ins
ert into `libros` (`titulo`, `descripcion`, `id_categoria`) values (Animi.,
 Voluptate illo ut recusandae adipisci iure atque quasi. In hic dolorum tem
pora. Quos quidem et cumque non., 1))

[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails (`laraveleloquentbasico`.`libro
s`, CONSTRAINT `libros_id_categoria_foreign` FOREIGN KEY (`id_categoria`) R
EFERENCES `categoria` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

After much research I know that it is the fault of the id_categoria field that has the foreign key, since I try to fill that field manually, and I get that error, what I do not know is what I'm doing wrong. The migration is fine, the problem is when using the db:seed, I always get that error. I have tried to make that field fillable in the model, and then I can not fill any field of the model, so I have removed it. Here are the codes.

Migration to create books

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreandoTablaLibros extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('libros',function(Blueprint $table){
           $table->increments('id');
           $table->string('titulo')->nullable();
           $table->text('descripcion')->nullable();
           $table->integer('id_categoria')->unsigned()->nullable();

           $table->SoftDeletes(); //update at
           $table->timestamps();//create at, update at

           //RELACIONES

           $table->foreign('id_categoria')
                      ->references('id')
                      ->on('categoria')
                      ->onDelete('cascade')
                      ->onUpdate('cascade');

       });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          Schema::drop('Libros');
    }
}

MIGRATION TO CREATE CATEGORIES

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreandoTablaCategoria extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       Schema::create('categoria',function(Blueprint $table){
            $table->increments('id');
            $table->string('nombrecategoria');
            $table->timestamps();

       });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('categoria');
    }
}

MIGRATION TO CREATE USERS

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre');
            $table->string('correo')->unique();
            $table->string('password');
            $table->enum('genero', array('f','m'));
            $table->string('bio');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

SEEDER TO CREATE BOOKS AND USERS

use Illuminate\Database\Seeder;
use Faker\Factory;

class generaDatos extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=1; $i <5 ; $i++) 
        {
        \DB::table('users')->insert(
                         array(
            'nombre' => $faker->name,
            'correo' => $faker->email,
            'password' => bcrypt('1'),
            'genero' => $faker->randomElement(array('m','f')),
            'bio' => $faker->text(255),

                            ));

         \DB::table('libros')->insert(
                         array(
            'titulo' => $faker->sentence(rand(1,5)),
            'descripcion' => $faker->text(rand(6,200)),
             'id_categoria' => $faker->randomElement(array('1','2','3')),

                            ));

        }

    }

}

SEEDER FOR CATEGORY

use Illuminate\Database\Seeder;

class CategoriaSeeder extends Seeder
{

   /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'PHP',
                       ));
              \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'HTML',
                       ));
                 \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'JAVASCRIPT',
                       ));
                    \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'CSS',
                       ));
    }
}

I do not put the models because they have practically nothing, but if you need them I will put them.

Any ideas?

1voto

Shaz Points 22941

You must run the Categories seeder before the other two.

The error occurs because you are trying to assign a value to category_id without such ids existing in the category table, so the relationship cannot be established.

0voto

To make it all related and at the same time of creation, you can do:

Users before or after, they are not related, those aside whenever you want.

And the categories and books in the same seeder, something like:

$id = DB::table('categoria')->insertGetId([...

With this it will save the id at the same time as you insert, and in the same seeder when you close category, below you open

DB::table('libros')->insert([<br>&emsp;&emsp;
           'id_categoria' => $id, ...

This way you can create in the same for loop 100 categories and 100 associated books at the same time.

I hope it works for you, it is not 100% your case, but it works great for users and their user profiles for example.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X