工厂创建具有不同数量关系的多个模型

Factory creating multiple models with different number of relationships

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

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

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

这没有用,每个 post 都有相同的(随机)评论数。

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

我怎样才能做到这一点?

更新: 应该有效: 灵感来自 apokryfos。如果这不起作用,那将:

for($i=0; $i<20; $i++)
{
    $times = rand(1,5);
    Post::factory()
     ->has(Comment::factory()->times($times))
     ->create();
}

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

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

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

我会使用工厂方法来做到这一点。像这样向您的 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();