我有表users
,posts
和comments
,用户有很多帖子,每个帖子都有很多评论(评论表中有post_id
),也有用户有很多评论,但匿名用户(评论表中的user_id
)并不完全需要,下面的代码为每个帖子添加一些注释,但user_id永远不会被评论的所有者填充。我想通过在$factory->define
之外的数组中注入注释来关联user_id。实际上我可以将随机user_id放在工厂内,但是随机用户总数必须与Seeder类中的值相同。
**CommentFactory.php**
$factory->define(App\Contact::class, function (Faker $faker) {
return [
// 'user_id' => $faker->randomElement([null, rand(0, 9)]),
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'contact' => $faker->phoneNumber,
'website' => $faker->domainName,
'subject' => $faker->sentence(),
'message' => $faker->paragraph(5),
];
});
**UserSeeder.php**
factory(App\User::class, 10)->create()->each(function ($user) {
$user->posts()->saveMany(factory(App\Post::class, rand(2, 10))->make());
$user->posts->each(function ($post) use ($user) {
// how to inject user_id value from here (comment factory)
$post->comments()->saveMany(factory(App\Comment::class, rand(2, 10))->make());
});
});
答案 0 :(得分:0)
您可以将一组属性/值传递给make方法:
factory(App\Comment::class, rand(2, 10))->make(['user_id'=>$user->id]);
编辑:只需迭代评论并分配随机用户ID:
factory(App\Comment::class, rand(2, 10))->create()->each(function($comment){
$comment->update(['user_id'=>\App\User::all()->random()->id]);
});
如果您想拥有随机匿名评论者:
factory(App\Comment::class, rand(2, 10))->create()->each(function($comment){
// pick either a random user_id or null;
$userId=array_random(\App\User::all()->random()->id, null);
$comment->update(['user_id'=>$userId]);
});