2

我正在使用以下代码创建 20 个帖子,每个帖子都有 3 条评论。

Post::factory()
    ->times(20)
    ->has(Comment::factory()->times(3))
    ->create()

相反,我想创建 20 个帖子,每个帖子都有随机数量的评论(例如,帖子 1 有 2 条评论,帖子 2 有 4 条评论,等等)

这不起作用,每个帖子都有相同(随机)数量的评论。

Post::factory()
    ->times(20)
    ->has(Comment::factory()->times(rand(1, 5)))
    ->create()

我怎样才能做到这一点?

4

3 回答 3

3

->times据我所知,如果您使用的是每个模型,则不可能有动态数量的相关模型。您可以尝试:

collect(range(0,19))
   ->each(function () {
       Post::factory()
          ->has(Comment::factory()->times(rand(1,5)))
          ->create();
});

这应该一个一个地创建 20 个帖子,每个帖子都有随机数量的评论。它可能会慢一点,但可能不会慢很多

于 2021-10-06T20:04:45.513 回答
3

我会使用工厂方法来做到这一点。Post像这样向您的工厂添加一个方法:

<?php
namespace Database\Factories\App;

use App\Comment;
use App\Post;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            // ...
        ];
    }

    public function addComments(int $count = null): self
    {
        $count = $count ?? rand(1, 5);
    
        return $this->afterCreating(
            fn (Post $post) => Comment::factory()->count($count)->for($post)->create()
        );
    }
}

然后在您的测试中,您可以像这样简单地调用它:

Post::factory()->count(20)->addComments()->create();
于 2021-10-06T20:46:21.703 回答
1

更新:应该可以:受 apokryfos 启发。如果这不起作用,那将:

for($i=0; $i<20; $i++)
{
    $times = rand(1,5);
    Post::factory()
     ->has(Comment::factory()->times($times))
     ->create();
}
于 2021-10-06T19:04:04.570 回答