使用 faker php 库模型工厂为每个用户创建多个评论

create multiple comments for each user with faker php library model factories

我想用 faker PHP 库生成虚假数据,但我想为每个用户创建 3 个评论。我应该怎么做?

我确实使用此代码为每个用户创建了 1 条评论:

factory(App\User::class, 50)->create()->each(function ($u) {
    $u->comments()->save(factory(App\Comment::class)->make());
});

我觉得应该是这样的:

factory(App\User::class, 50)->create()->each(function ($u) {
    $u->comments()->saveMany(factory(App\Comment::class, 3)->make());
});

In case you want to create more than one comment, use ->saveMany() instead of ->save(). ->save() takes in an instance of Illuminate\Database\Eloquent\Model while ->saveMany() an instance of Illuminate\Database\Eloquent\Collection which is what factory(App\Comment::class, 3)->make() returns.

Note: I would randomize the number using rand(1, 5).

我找到了解决方案:)

我使用了 dd(factory(Comment::class,mt_rand(0,3))->make()),我发现它 returns 创建了 3 条评论的集合,所以我使用 foreach 使用这些代码行为我的用户创建了所有这 3 条评论:

$comments = factory(Comment::class,mt_rand(0,3))->make();
  for ($i=0; $i < $comments->count(); $i++) { 
  $u->comments()->save($comments[$i]);
}