PHP Laravel seeding - foreign id

42 Views Asked by At

The code below is a factory that is used in my database seeder. The issue is that some comments are under a post and others under another comment. That said, I need to find a way to generate a foreign_id relationship for either a post or a comment, not both.

Additionally, the big challenge is that the comment needs to have a foreign_id relationship to another comment in some cases. Right now, with the code below, NULL will always be in the database column comment_id... I guess it doesn't acknowledge the newly created records in that seed run...

class CommentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'user_id' => User::inRandomOrder()->first(), // Gets a random user ID
            'post_id' => Post::inRandomOrder()->first(),
            'comment_id' => Comment::inRandomOrder()->first(), // !!! THIS LINE HERE !!!
            'content' => fake()->paragraph(2)
        ];
    }
}

I tried to use a rand(0, 1) in an if statement that would create the comment under either a post or another comment.

The issue is that when it's time to create a comment under another comment, the foreign id for comment_id is always null since my database has no comments when I run the seeder.

1

There are 1 best solutions below

0
Payette1996 On

HERE IS THE ANSWER: I had to leverage the configure() method and the method afterCreating()

class CommentFactory extends Factory
{
    public function definition()
    {
        return [
            'user_id' => User::inRandomOrder()->first()->id,
            'content' => $this->faker->paragraph(2),
        ];
    }

    public function configure()
    {
        return $this->afterCreating(fn (Comment $comment) => 
            rand(0, 1)
                ? $comment->update(['post_id' => Post::inRandomOrder()->first()->id])
                : $comment->update(['comment_id' => Comment::inRandomOrder()->first()->id])
        );
    }
}