Laravel - Seeding Many-to-Many Relationship

后端 未结 4 872
不思量自难忘°
不思量自难忘° 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:49

    You can use attach() or sync() method on a many-to-many relationship.

    There are multiple ways you can approach this. Here one of them:

    // Populate roles
    factory(App\Role::class, 20)->create();
    
    // Populate users
    factory(App\User::class, 50)->create();
    
    // Get all the roles attaching up to 3 random roles to each user
    $roles = App\Role::all();
    
    // Populate the pivot table
    App\User::all()->each(function ($user) use ($roles) { 
        $user->roles()->attach(
            $roles->random(rand(1, 3))->pluck('id')->toArray()
        ); 
    });
    

提交回复
热议问题