Udders
Udders

Reputation: 6976

laravel database seeder adding add foreign key id randomly to seeds

I am trying to create seeders for testing purposes. I have users that belongs to a room via a room id, these rooms are created via a room seeder, in my users seeder, I create a user and update the room_id attribute like this,

factory(App\User::class, 150)->create([
        'host' => false,
        'room_id' =>  App\Room::inRandomOrder()->first()->id
    ]);

My problem is that all users generated here, all get the same room id, how can a truly get a random room id from the database and use it in my seeder?

Upvotes: 3

Views: 3368

Answers (4)

rez
rez

Reputation: 2077

I had the same problem with seeding. The problem is that, you are overriding the factory's default model attributes by passing an array of "values". You are passing the value of App\Room::inRandomOrder()->first()->id to the create method. So you would have all users with the same room_id.

To solve this issue, in laravel 8, you can move the 'room_id' => Room::inRandomOrder()->first()->id to your UsersFactory definition:

class UsersFactory {
...

    public function definition()
    {
        return [
            'room_id' => Room::inRandomOrder()->first()->id
        ];
    }
...
}

And create users like this,

App\User::factory()->count(150)->create([
    'host' => false
]);

In older version of laravel, define your factory as below:

$factory->define(App\User::class, function ($faker) use ($factory)  {
    return [
        'room_id' => Room::inRandomOrder()->first()->id
    ];
});

And create users like this,

factory(App\User::class, 150)->create([
        'host' => false,
    ]);

Upvotes: 1

Utkarsh Raval
Utkarsh Raval

Reputation: 16

Try this one. Also, make sure that you have multiple auto incremented room entries in the room table.

$factory->define(App\User::class, function ($faker) use ($factory)  {
    return [
        'host' => false,
        'room_id' => $factory->create(App\Room::class)->id
    ];
});

Upvotes: 0

Utkarsh Raval
Utkarsh Raval

Reputation: 16

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $users = factory(\App\User::class, 150)->create([
        'host' => false,
        'room_id' => $this->getRandomRoomId()
    ]);
}

private function getRandomRoomId() {
    $room = \App\Room::inRandomOrder()->first();
    return $room->id;
}

Try this one. It works for me. Hopefully it works for you.

Upvotes: 0

Johannn
Johannn

Reputation: 138

Try:

App\Room::all()->random()->id

Upvotes: 0

Related Questions