简体   繁体   中英

Laravel 4 seed database table with relationship

Usually we create a database seed file like this to seed a database table:

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);
       }
    }

}

But how can we seed table with relationship? For example, table users with table memberdetail:

Users Table:

id, email, password, name

memberdetail table:

id, userid, gender, address, dob

memberdetail table's userid column will show the id which links to the id on users table. How can we seed these 2 tables?

Thank you.

Assume you have a model called 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();
           }
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM