php - How to seed a table with a foreign key constraint laravel

How can I seed my Comments table with comments.post_id as Foreign Key to post.id.

I have a Factory for the Comments table but not for the Post table.The Post table I populate manually so I can not link Factories.

I have a problem with adding a comment, because of the FK constraint. I insert a post.id manually, but don;t know how to let Laravel choose an id automatically.

Thanks in advance, Sam

CommentFactory

<?php

namespace Database\Factories;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;


class CommentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Comment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'post_id'=> 38,
            'author' => $this->faker->name(),
            'comment' => $this->faker->realText(150),
            'approved' => 0,
        ];
    }
}

Answer

Solution:

Post::all()->random()->id, always fetch any random post ID and assign it the comment.

<?php

namespace Database\Factories;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;


class CommentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Comment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'post_id'=> Post::all()->random()->id, <---- try this.
            'author' => $this->faker->name(),
            'comment' => $this->faker->realText(150),
            'approved' => 0,
        ];
    }
}

Answer

Solution:

I used pluck() to create an array with all post.id

$posts = Post::all()->pluck('id')->toArray();

and used randomElement() to pick a random id as a post_id

$post_id = $this->faker->randomElement($posts);

Many thanks for the suggestions!

Source