Reputation: 19463
Usually we create a database seed file like this to seed a database table:
class UsersSeeder extends DatabaseSeeder {
public function run()
{
$users = [
[
'email' => '[email protected]',
'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.
Upvotes: 0
Views: 2469
Reputation: 12199
Assume you have a model called MemberDetail
.
class UsersSeeder extends DatabaseSeeder {
public function run()
{
$users = [
[
'email' => '[email protected]',
'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();
}
}
}
Upvotes: 1