Nevermore
Nevermore

Reputation: 1743

Many to Many third column seed in laravel

I have two tables which are users and groups. And they have many-to-many relation. Actually, i want to store the which user in which group info and user role in group. So i created a migration table, group_user_table...

public function up() {
    Schema::create('group_user', function (Blueprint $table) {
        $table->integer('user_id')->unsigned();
        $table->integer('group_id')->unsigned();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('group_id')->references('id')->on('groups');
    });
}

And how i seed :

$groupQuantity = 26;
$userQuantity = 20;

factory(User::class, $userQuantity)->create();

factory(Group::class, $groupQuantity)->create()->each(function ($foo) {
        $foo->users()->sync(
            User::all()->random(rand(1,20))
        );
});

It works perfect, but i want to add user role in pivot_table like :

$table->integer('type')->unsigned()->comment('0- Owner, 1- Admin, 2- User');

I could add in migration but i have no idea to seed ? (It gives an error, type doesnt have default value, when i try to seed.)

Or should i make second pivot table to user roles ?

Laravel 5.4...

Upvotes: 0

Views: 65

Answers (1)

pseudoanime
pseudoanime

Reputation: 1593

You can modify the seeder for the group_user by adding a DB function to it.

for($i=0;$i<rand(0,10),$i++) {
    $user = factory(User::class, $userQuantity)->create();
    factory(Group::class, $groupQuantity)->create()->each(function ($foo) {
        DB::table('group_user')->insert([
            [
                'user_id' => $user->id,
                'group_id' => $foo->id,
                'type'    => rand(0,2)
            ],
        ]);        
    });         
}

Upvotes: 1

Related Questions