laravelのfactoryでコメントとコメントの子的なのを作成する

どんなの作るか

ブログのコメントとかでよくある 記事のコメント コメントのコメント とかできるやつ

コード

Factory

<?php

namespace Database\Factories;

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

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Comment>
 */
class CommentFactory extends Factory
{
    private static int $sequence = 1;
    private static int $user_id = 1;
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'user_id' => fn () => self::$sequence++,
            'question_id' => fake()->numberBetween(1,100),
            'parent_id' => NULL,
            'body' => fake()->realText($maxNbChars =100),
        ];
    }

    public function child(): static
    {
        return $this->state(fn (array $attributes) => [
            'parent_id' => Comment::all()->random(),
        ]);
    }

    public function configure()
    {
        return $this->afterMaking(function (Comment $comment) {
            //
        })->afterCreating(function (Comment $comment) {
            if (self::$user_id !== $comment->user_id) {
                self::$user_id = $comment->user_id;
                self::$sequence = 1;
            }
        });
    }
}

Seeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Comment;


class CommentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Comment::factory()
            ->count(1000)
            ->create();
        for ($i = 0; $i < 3; $i++) {
            Comment::factory()
                ->count(1000)
                ->child()
                ->create();
        }
    }
}

こうすれば
1000個のユーザーで
1000件の記事へのコメント
1000件*3のコメントへのコメントが作成できる
各ユーザーは4回書き込んだことになる

参考

Laravel Factoryで単純に連番を振ったり〇〇単位で連番を振る方法 │ wonwon eater

Eloquent:ファクトリ 10.x Laravel