7

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
    ]);
}
miken32
  • 42,008
  • 16
  • 111
  • 154
Newb 4 You BB
  • 1,205
  • 1
  • 11
  • 30

2 Answers2

12

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)
    ];
}

Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30
5

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.

Peppermintology
  • 9,343
  • 3
  • 27
  • 51
  • This is definitely an option but it would be more ideal if the blog post factory created the blog post and just looked to see what users exist from the user factory. – Newb 4 You BB Jan 21 '21 at 01:10
  • 1
    In which case the answer by [Stefano](https://stackoverflow.com/a/65819881/281278) is probably what you’re after. – Peppermintology Jan 21 '21 at 01:21