Newb 4 You BB
Newb 4 You BB

Reputation: 1355

Laravel 8 - Factories & Foreign Keys

I haven't been able to locate how to manage foreign keys when creating Factories and Seeders.

I have a users table and a blog_posts table. The blog_posts table has a foreign key user_id that references users.id. I would like to seed my database with users and blog posts.

I have seen how to create a new user for each seeded blog post with the following:

/**
 * Define the BlogPost model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::factory(),
        'created_at' => now(),
        'updated_at' => now(),
        'title' => $this->faker->words(5, true),
        'body' => $this->faker->paragraphs(6, true)
    ];
}

...but I would like to reference existing users since I am performing the database seed like so:

/**
 * Seed the application's database.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UsersTableSeeder::class, 
        BlogPostsTableSeeder::class
    ]);
}

Upvotes: 8

Views: 4987

Answers (2)

Peppermintology
Peppermintology

Reputation: 10210

Assuming your User model has a hasMany relationship called blogPosts, you could do the following:

User::factory()
    ->hasBlogPosts(6)
    ->create();

This would create your User and 6 associated BlogPosts.

Upvotes: 5

Stefano Amorelli
Stefano Amorelli

Reputation: 4854

We can retrieve a random existing User and assign it in the BlogPost Factory as follows:

/**
 * Define the BlogPost model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::inRandomOrder()->first()->id,
        'created_at' => now(),
        'updated_at' => now(),
        'title' => $this->faker->words(5, true),
        'body' => $this->faker->paragraphs(6, true)
    ];
}

Upvotes: 13

Related Questions