Reached
498
11
Laravel

Seeding relationships

Posted 4 years ago by Reached

Hey guys,

Im trying to seed my database, with some products that belong to some categories. I seeded the database with my categories, but when I try to attach the products to (random) categories, i run into this issue:

  [Illuminate\Database\QueryException]                                                                             
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constrain  
  t fails (`webshop`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES  
   `categories` (`id`)) (SQL: insert into `products` (`product_name`, `product_image`, `product_price`, `updated_  
  at`, `created_at`) values (dolorem, http://lorempixel.com/400/400/9032255, 2015-07-15 12:34:56, 2015-07-15 12:3  
  4:56, ?))                                                                                                        
                                                                                                                                                                                                                                 
  [PDOException]                                                                                                   
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constrain  
  t fails (`webshop`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES  
   `categories` (`id`))

And here is my code:

<?php

use Illuminate\Database\Seeder;
use App\Category;
use App\Product;

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

        $categories = Category::get()->lists('id')->all();

        foreach(range(1,50) as $index){
            $products = Product::create([
                'product_name' => $faker->word,
                'product_image' => $faker->imageUrl($width = 400, $height = 400),
                'product_price' => $faker->randomNumber(2),
                'category_id' => $faker->randomElement($categories),
            ]);
        }
    }
}

Can anyone help?

Please sign in or create an account to participate in this conversation.