Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

Laravel - Seeding Many-to-Many Relationship

I have a users table and a roles table that has a many-to-many relationship. These two tables are connected to a junction table called role_user.

This is a model of the tables and its connections.

Below are the Models in my Laravel project:

User

namespace App;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('AppRole');
    }
}

Role

namespace App;

use IlluminateDatabaseEloquentModel;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('AppUser');
    }
}

Below is the Factory file in the Laravel project:

$factory->define(AppUser::class, function (FakerGenerator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
    ];
});

$factory->define(AppRole::class, function (FakerGenerator $faker) {
    return [
        'role' => $faker->realText($maxNbChars = 2),
        'description' => $faker->realText($maxNbChars = 20),
    ];
});

Below is the Seed file in the Laravel project:

public function run()
{
    factory(AppUser::class, 50)->create()->each(function ($u) {
        $u->roles()->save(factory(AppRole::class)->make());
    });

    factory(AppRole::class, 20)->create()->each(function ($u) {
        $u->users()->save(factory(AppUser::class)->make());
    });
}

This should populate the users table and the roles table but how do I go about populating the role_user table? (I don't have a Model file for the junction table.)

I'm very new at this so any help would be appreciated. Thanks.

question from:https://stackoverflow.com/questions/45269146/laravel-seeding-many-to-many-relationship

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(AppRole::class, 20)->create();

// Populate users
factory(AppUser::class, 50)->create();

// Get all the roles attaching up to 3 random roles to each user
$roles = AppRole::all();

// Populate the pivot table
AppUser::all()->each(function ($user) use ($roles) { 
    $user->roles()->attach(
        $roles->random(rand(1, 3))->pluck('id')->toArray()
    ); 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...