种子组合键在枢轴表laravel 4

时间:2013-09-03 06:39:12

标签: database-design laravel laravel-4 pivot-table seeding

我在laravel 4项目中使用了JeffreyWay Laravel-4-Generators。我有一个用户和一个权限表和一个数据透视表user_privilage。我使用generate:seed为用户和权限表设定种子,但我不知道如何为user_privilage表设定种子。我尝试建立一个网站,我想将基本项目播种到表格中,以查看网站的运作方式。怎么做?

2 个答案:

答案 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');