lq003's avatar
Level 1

How to go about seeding foreign keys?

Hello, I'm a complete beginner to Laravel and I'm attempting to use seeders to seed a database I'm using for a test project of an inventory management system. However, I run into issues when I attempt to seed tables that have foreign keys. I get errors such as: General error: 1364 Field 'category_id' doesn't have a default value"

Of course, I get that this is because the key needs to have a value, but since this is dummy data, I'm not quite sure of how to go about adding foreign keys. I'm using faker to generate random values for the rest of the attributes and I didn't run into any issues with that, it's just the foreign keys that are giving me a headache.

This is the relevant code I'm using if it helps:

ProductFactory

    public function definition(): array
    {
        return [
            'name' => $this->faker->word(),
            'description' => $this->faker->sentence(),
            'base_price' => $this->faker->randomFloat(4),
            'base_cost' => $this->faker->randomFloat(4)
        ];
    }

ProductSeeder

    public function run(): void
    {
        Product::factory()->count(10)->create();	
    }
0 likes
2 replies
lq003's avatar
Level 1

@Ben Taylor Huh, that was surprisingly simple. Thanks

1 like

Please or to participate in this conversation.