Laravel - Seeding Many-to-Many Relationship

后端 未结 4 884
不思量自难忘°
不思量自难忘° 2020-12-07 14:48

I have a users table and a roles table that has a many-to-many relationship. These two tables ar

4条回答
  •  难免孤独
    2020-12-07 15:22

    A much cleaner method can be: after you define the factory for App\User and App\Roles you can call the afterCreating method like this:

    $factory->define(App\User::class, function ...);
    $factory->define(App\Role::class, function ...);
    
    $factory->afterCreating(App\User::class, function ($row, $faker) {
        $row->roles()->attach(rand(1,20));
    });
    

    Then in Seeds you first create the roles, then the users

    public function run()
    {
        factory(App\Role::class, 20)->create();
        factory(App\User::class, 50)->create();
    }
    

    Now you have 50 users each of them with one role attached.

提交回复
热议问题