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