Reputation: 2191
Laravel 8 has some changes in database seeding. I want to seed some related models with database seeder.
There are three models: User, Post, Comment
.
A user has many posts, and a post has many comments.
Now I want to create some users with some related posts and some comments related to the post.
I can only seed some user and the related posts, but not comments related to the posts.
I have the code below:
User::factory(10)->hasPosts(rand(5, 10))->create();
It created 10 users and 5 to 10 related posts for each user. What can I do to seed the comments? Can I do it in the single line or do I need to to to new line? Note: I have created the factory for each model.
Upvotes: 2
Views: 1365
Reputation: 12845
You can try
User::factory(10)->has(
Post::factory(random_int(5,10))
->has(Comment::factory(random_int(2,3)))
)->create();
Upvotes: 7