Laravel - Seeding Many-to-Many Relationship

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

提交回复
热议问题