@bwrigley you have to change create to make when passing factories to saveMany methods, the same way as you do in ForumReplyFactory.
Mar 4, 2020
16
Level 5
Cascading afterCreatingState() in factories
I'm creating a forum which has these relationships:
ForumCategory hasmany ForumThread hasmany ForumReply
and both ForumThread and FormReply hasmany ForumLike
I'm now trying to set up factories and seeders and I'm using the afterCreatingState() to create relationship models:
ForumCategoryFactory:
$factory->define(ForumCategory::class, function (Faker $faker) {
return [
'name' => implode(' ', $this->faker->words(3)),
'description' => $this->faker->text(600),
];
});
$factory->afterCreatingState(ForumCategory::class, 'with-threads', function ($category) {
$category->forumThreads()
->saveMany(factory(ForumThread::class, rand(0,6))
->states('with-user','with-replies','with-likes')
->create());
});
ForumThreadFactory:
$factory->define(ForumThread::class, function (Faker $faker) {
return [
'title' => implode(' ',$faker->words(3)),
'message' => $faker->text(600),
'is_resolved' => false,
'is_locked' => false,
'is_pinned' => $faker->boolean(),
'is_live' => true,
'is_visible' => true,
'view_count' => $faker->numberBetween(0,1000),
'user_id' => null,
'forum_category_id' => null,
];
});
$factory->afterCreatingState(ForumThread::class, 'with-replies', function ($thread) {
$thread->forumReplies()
->saveMany(factory(ForumReply::class, rand(0,6))
->states('with-user')
->create());
});
$factory->afterCreatingState(ForumThread::class, 'with-likes', function ($thread) {
$thread->forumLikes()
->saveMany(factory(ForumLike::class, rand(0,6))
->states('with-user')
->create());
});
///
ForumReplyFactory:
$factory->define(ForumReply::class, function (Faker $faker) {
return [
'message' => $faker->text(600),
'is_solution' => $faker->boolean(),
'is_locked' => $faker->boolean(),
'is_pinned' => $faker->boolean(),
'is_visible' => true,
'user_id' => null,
'forum_thread_id' => null,
];
});
$factory->afterCreatingState(ForumReply::class, 'with-likes', function ($reply) {
$reply->forumLikes()
->saveMany(factory(ForumLike::class, rand(0,6))
->states('with-user')
->make());
});
///
For the most part it is working, the category is created as are threads and replies and likes. The threads have relationships to the category.
The problem I'm having is that the ForumReply and ForumLike models all have null 'forum_thread_id`
Thanks for any guidance or spotting of glaring errors.
Please or to participate in this conversation.