If a User has many posts, and a post belongs to user, it's simple to do:
$factory->define(App\Post::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
// Creates a User for every Post
return factory(App\User::class)->create()->id;
}
];
});
How do I accomplish the opposite? Instead, creating say 5 posts when a user is created and associating that post to the newly created user?
~Edit I am using laravel 5.2, and I've declared my model relationships in my models, so I now have:
$user = factory(App\User::class)->create();
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);
// Great, now I have a User and 3 Posts associated with that user.
// However, now, I want let's say, 5 votes per post.
// I can't call $posts->votes(), so I iterate
foreach ($posts as $post) {
$votes = factory(App\Votes::class, 5)->make();
$post->votes()->saveMany($votes);
}
Then any other relation to votes, etc would just be nested in the foreach.