I have the following structure in my Laravel 5.2 app:
User: id name ...
Post: id title body user_id (fk)
Comment: id body user_id (fk) post_id (fk)
I want to create few users (20), for each users a random number of Posts, and to each post, a random number of comments(even a fixed number it`s ok).
I can create users and assign Posts to each, but i can't assign comments to each post: i have this:
factory(App\User::class, 20)->create()->each(function($u) {
$u->posts()->saveMany(factory(App\Post::class, 5)->make();
});
I found something but didn`t work:
factory(App\Comment::class, 100)->create()->each(function($u) {
$u->user()->sync(
App\User::all()->random(3)
);
});
NOTE: i made the relationship between models like this: User hasMany Post, User hasMany Comment, Post hasMany Comment, Comment belongsTo Post, Comment belongsTo User