LARAVEL 5.2 - Integrity constraint violation: 1452 Can not add or update to child row: - Problem relating tables

2

I'm trying to fill some tables with the faker library, so far I have not had any problems, since they were mini-projects and the tables were not related, but now, I'm starting with relations in laravel and I get an error that does not I can solve.

There are three tables, user books, and category

This is the error:

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 a lot of research, I know it's the field's id_categoria field that has the foreign key, since I try to fill in that field manually, and I miss that error, what I do not know is what I'm doing wrong. Migration is good, the problem is to use the db: seed, that error always comes out. I tried to make that field fillable in the model, and then if I can not fill in any field of the model, so I have removed it. Here 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?

    
asked by KurodoAkabane 18.05.2016 в 20:02
source

2 answers

1

You must run the seeder of Categories before the other two.

The error occurs because you try to assign a value to category_id without there being such ids in the category table, so the relationship can not be established.

    
answered by 19.05.2016 / 10:35
source
0

To do everything related and at the same time of the creation, you can do:

The users before or after, are not related, those apart whenever you want.

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

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

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

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

So you can create in the same loop "for" 100 categories and 100 associated books at the same time

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

    
answered by 04.02.2017 в 20:17