我在laravel 4项目中使用了JeffreyWay Laravel-4-Generators。我有一个用户和一个权限表和一个数据透视表user_privilage
。我使用generate:seed
为用户和权限表设定种子,但我不知道如何为user_privilage
表设定种子。我尝试建立一个网站,我想将基本项目播种到表格中,以查看网站的运作方式。怎么做?
答案 0 :(得分:5)
我解决了这个问题。我使用:
创建了一个数据透视表role_user
种子
php artisan generate:seed role user
并在RoleUserTableSeeder
中输入:
$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);
db:seed
完美无缺。
答案 1 :(得分:1)
首先,我为特权表创建了一个Seeder
<强> 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'
]);
然后我将播放users表和数据透视表
<强> 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));
然后在 DatabaseSeeder.php
上 $this->call('PrivilegesTableSeeder');
$this->call('UsersTableSeeder');