Laravel - Seeding Many-to-Many Relationship

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

    0 讨论(0)
  • 2020-12-07 15:36

    Just for a seeder you can use something like this:

       for ($i = 0; $i < 50; $i++) {
            $user = factory(App\User::class)->create();
    
            $role = factory(App\Role::class)->create();
    
            DB::table('role_user')->insert([
                'user_id' => $user->id,
                'role_id' => $role->id
            ]);
        }
    

    But normally you need to define relation like has many through https://laravel.com/docs/5.4/eloquent-relationships#has-many-through

    Then you will be able to use:

    $user->roles()->save($role);
    
    0 讨论(0)
  • 2020-12-07 15:45

    Another way is to use saveMany() function

    public function run()
    {
    
       factory(App\User::class,3)->create();
    
       $roles = factory(App\Role::class,3)->create();
    
       App\User::All()->each(function ($user) use ($roles){
          $user->roles()->saveMany($roles);
       });
    }
    
    0 讨论(0)
  • 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()
        ); 
    });
    
    0 讨论(0)
提交回复
热议问题