Home > Blockchain >  Integrity constraint violation - Laravel
Integrity constraint violation - Laravel

Time:10-11

I am trying to create a relationship between categories and products. I have provided the various columns for both tables and I am trying to link them using a foreign id (the category_id from the category table) but I keep getting this error.

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failsIntegrity constraint violation: 1452 Cannot add or update a child row but it does not answer the question

This is my Category table

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

And this is the product table

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('category_id');
        $table->string('name');
        $table->string('description');
        $table->string('image');
        $table->integer('price');
        $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
        $table->timestamps();
    });
}

This is the category model.

class Category extends Model
{
 use HasFactory;

protected $fillable = [
    'name',
];


public function products()
{
    return $this->hasMany(Product::class);
}

}

This is the product model

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'image',
        'price',
        'category_id',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = $value * 100;
    }
}

This is my Product Factory class

<?php
    
    namespace Database\Factories;
    
    use Illuminate\Database\Eloquent\Factories\Factory;
    
    class ProductFactory extends Factory
    {
       
        public function definition()
        {
            return [
                'name'=>$this->faker->unique()->word(),
                'description'=>$this->faker->text(),
                'image'=>$this->faker->imageUrl(100, 100),
                'price'=>$this->faker->numberBetween($min = 50, $max = 100),
                'category_id'=>$this->faker->randomDigit()
            ];
        }
    }

This is my db seeder class

class DatabaseSeeder extends Seeder

    {
       
        public function run()
        {
    
            Product::factory(20)->create();
        }
    }

This is the full error code I am getting please after running the db:seed

 INFO  Seeding database.  

Illuminate\Database\QueryException

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`econs`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE) (SQL: insert into `products` (`name`, `description`, `image`, `price`, `category_id`, `updated_at`, `created_at`) values (omnis, Facere autem excepturi velit dolorem voluptas. Dignissimos laboriosam quia numquam sint harum officia eum. A aspernatur ratione fuga ut nesciunt sit. Ex nisi maxime quas., https://via.placeholder.com/100x100.png/006611?text=aut, 5700, 4, 2022-10-10 11:49:55, 2022-10-10 11:49:55))

  at vendor/Laravel/framework/src/Illuminate/Database/Connection.php:759
    755▕         // If an exception occurs when attempting to run a query, we'll format the error
    756▕         // message to include the bindings with SQL, which will make this exception a
    757▕         // lot more helpful to the developer instead of just the database's errors.
    758▕         catch (Exception $e) {
  ➜ 759▕             throw new QueryException(
    760▕                 $query, $this->prepareBindings($bindings), $e
    761▕             );
    762▕         }
    763▕     }

       16 vendor frames 
  17  database/seeders/DatabaseSeeder.php:26
      Illuminate\Database\Eloquent\Factories\Factory::create()

       23 vendor frames 
  41  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

CodePudding user response:

You're using $this->faker->randomDigit() which creates a random digit, and doesn't care if the category ID exists or not. For your factory, you can grab a random category and use it's id:

'category_id'=>Category::inRandomOrder()->first()->id

CodePudding user response:

Try changing $table->unsignedInteger('category_id'); to $table->unsignedBigInteger('category_id'); and also confirm that there is category id 4 present in Categories table

  • Related