panthro
panthro

Reputation: 24099

Seeding a table that has multiple relationships?

I have a comments table that belongsTo both a user table and an article table.

How can the table be seeded so that both the user and article foreign key is complete?

After looking through various examples, I found that you could seed the user then attach/save other models...

factory(User::class, 100)->create()->each(function ($user) {

$articles = factory(Article::class, 5)->make();
$user->article()->saveMany($articles);

But how can the same be done for comments with two foreign keys?

Upvotes: 3

Views: 61

Answers (1)

porloscerros Ψ
porloscerros Ψ

Reputation: 5098

Not tested, but it should work, or at least give you the idea.

In the case of comments, you can create a factory like this one, where you will assign the foreign keys taking a random User and Article:

$factory->define(Comment::class, function (Generator $faker) {
    return [
        'content' => $faker->paragraph,
        'user_id' => User::inRandomOrder()->select('id')->first()->id,
        'article_id' => Article::inRandomOrder()->select('id')->first()->id
    ];
});

Note that both User and Article records must exist for you to assign their ids to foreign keys. So to use the factory in the seeder, you will have call it after the users and articles be inserted:

// do the inserts of users and articles, I left this as you show it in the question
factory(User::class, 100)->create()->each(function ($user) {
    $articles = factory(Article::class, 5)->make();
    $user->article()->saveMany($articles);
});

factory(Comment::class, 50)->create();

Upvotes: 2

Related Questions