我在我的 laravel 4 项目中使用了 JeffreyWay Laravel-4-Generators 。我有一个用户和一个权限表和一个数据透视表user_privilage
。我使用 agenerate:seed
为用户和权限表播种,但我不知道如何播种该user_privilage
表。我尝试创建一个网站,我想将基本项目播种到表格中以查看网站的工作方式。怎么做?
问问题
2002 次
2 回答
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
工作完美。
于 2013-09-03T09:19:22.973 回答
1
首先,我为权限表创建一个 Seeder
特权TableSeeder
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'
]);
然后我将把用户表和数据透视表一起播种
用户TableSeeder
// 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');
于 2014-06-19T08:35:12.553 回答