Laravel 4种子数据库表有关系

时间:2014-01-08 04:19:45

标签: php mysql database laravel-4

通常我们创建一个这样的数据库种子文件来为数据库表设定种子:

class UsersSeeder extends DatabaseSeeder {

    public function run()
    {
        $users = [
            [
              'email' => 'mymail@mail.com',
              'password' => Hash::make('123456'),
              'name' => 'Admin'
            ]
       ];

       foreach ($users as $user) {
         User::create($user);
       }
    }

}

但是我们怎样才能与关系一起播种呢?例如,具有表memberdetail的表用户:

用户表:

id, email, password, name

memberdetail table:

id, userid, gender, address, dob

memberdetail table的userid列将显示链接到users表上id的id。我们怎样才能为这两张桌子播种?

谢谢。

1 个答案:

答案 0 :(得分:1)

假设您有一个名为MemberDetail的模型。

    class UsersSeeder extends DatabaseSeeder {

        public function run()
        {
            $users = [
                [
                  'email' => 'mymail@mail.com',
                  'password' => Hash::make('123456'),
                  'name' => 'Admin'
                ]
           ];

           foreach ($users as $user) {
             $user = User::create($user);

             $memberDetail = new MemberDetail;
             $memberDetail->userid = $user->id;

             // Fill up gender, address, dob
             // i am not sure what data you have for gender, address and dob.
             $memberDetail->gender = 'Male';
             $memberDetail->address = 'Australia';
             $memberDetail->dob = '2014-01-08';
             $memberDetail->save();
           }
        }

}