Reputation: 520
I wanted to make a post seeder with users and comments as mentioned in the relationship section in the laravel documentation https://laravel.com/docs/5.5/database-testing
$users = factory(App\User::class, 3)
->create()
->each(function ($u) {
$u->posts()->save(factory(App\Post::class)
->create()
->each(function($p){
$p->comments()->save(factory(App\Comment::class,5)
->create()
->each(function($c){
$c->user()->save(factory(App\User::class)
->make()
);
})
);
})
);
}
);
Expected output was to have 3 users having posts with 5 comments each.
But error occurred:
In Builder.php line 2459: Call to undefined method Illuminate\Database\Query\Builder::save()
Upvotes: 3
Views: 3687
Reputation: 564
try this method:
$users = factory(App\User::class, 5)->create();
foreach ($users as $user) {
$articles = factory(App\Article::class, 5)->create([
'user_id' => $user->id
]);
foreach ($articles as $article) {
factory(App\Comment::class, 5)->create([
'article_id' => $article['id']
]);
}
}
Upvotes: 0
Reputation: 347
There are several problems in your solution for example
$p->comments()->save(factory(App\Comment::class,5)
you are trying to save multiple comments with save() which will result in error you should use saveMany() instead. However the solution to your problem can be this:
$users = factory(App\User::class, 3)->create()
->each(function ($user) {
$user->posts()->saveMany(factory(App\Post::class, 5)->make());
});
foreach ($users as $user){
foreach ($user->posts as $post){
$post->comments()->saveMany(factory(App\Comment::class, 5)->make());
}
}
this will work as expected.
Upvotes: 0
Reputation: 4412
try this :
$users = factory(App\User::class, 3)
->create()
->each(function ($u) {
$u->posts()->save(factory(App\Post::class)->make())
->each(function($p){
$p->comments()->save(factory(App\Comment::class,5)->make())
->each(function($c){
$c->user()->save(factory(App\User::class)
->make()
);
})
);
})
);
}
);
Solution with regular foreach
$users = factory(App\User::class, 3)->create();
foreach($users as $user){
$post = $user->posts()
->create(factory(App\Post::class)->make()->toArray());
$post->comments()
->createMany(
factory(App\Comment::class, 5)
->make(['user_id' => factory(App\User::class)
->create()->id])->toArray());
}
Upvotes: 1