Вопрос

I used JeffreyWay Laravel-4-Generators in my laravel 4 project. I have a users and a privileges table and a pivot table user_privilage. I used a generate:seed to seed a user and privileges table, but I don't know how to seed the user_privilage table. I try to make a site and I want to seed basic items to the tables to view how the website works. How to do that?

Это было полезно?

Решение

I solved the problem. I created a pivot table role_user seed using:

php artisan generate:seed role user

and in RoleUserTableSeeder I type that:

$adminRole = Role::where('name','=','Admin')->first()->id;
$userRole = Role::where('name','=','Registred user')->first()->id;
$admin = User::where('username','=','admin')->first()->id;
$user = User::where('username','=','user')->first()->id;
$role_user = array(
    array('role_id' => $adminRole, 'user_id'=>$admin, 'active'=>1, 'created_at' => new DateTime, 'updated_at' => new DateTime,),
    array('role_id' => $userRole, 'user_id'=>$user, 'active'=>1, 'created_at' => new DateTime, 'updated_at' => new DateTime,)
);

// Uncomment the below to run the seeder
DB::table('role_user')->insert($role_user);

And db:seed work perfectly.

Другие советы

First I create a Seeder for the privileges table

PrivilegesTableSeeder

Privilege::create([
    'id'   => '1',
    'privilege' => 'privilege 1'
]);

Privilege::create([
    'id'   => '2',
    'privilege' => 'privilege 2'
]);

Privilege::create([
    'id'   => '3',
    'privilege' => 'privilege 3'
]);

Privilege::create([
    'id'   => '4',
    'privilege' => 'privilege 4'
]);

Privilege::create([
    'id'   => '5',
    'privilege' => 'privilege 5'
]);

Privilege::create([
    'id'   => '6',
    'privilege' => 'privilege 6'
]);

Then I will then be seeding the users table along with the pivot table

UsersTableSeeder

// Attach all privileges to admin 
$user = new User;
$user->email = 'admin@admin.com';
$user->password   = 'pass';
$user->save();

$user->privileges()->attach(array(1,2,3,4,5,6));

// Attach privileges 1 & 3 to 2nd user
$user = new User;
$user->email = 'account2@user.com';
$user->password = 'pass';
$user->save();

$user->privileges()->attach(array(1,3));

Then on DatabaseSeeder.php

 $this->call('PrivilegesTableSeeder');

 $this->call('UsersTableSeeder');
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top