Laravel种子关系问题

时间:2018-03-20 06:25:26

标签: laravel factory relation laravel-eloquent

我希望将数据添加到administrators表中,以便为插入到users表中的每个数据添加数据。这里' S UserFactory.php

$factory - > define(App\ User::class, function(Faker $faker) {
  return [
    'id' => $faker - > unique() - > isbn10,
    'email' => $faker - > unique() - > safeEmail,
    'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
    'remember_token' => str_random(10),
  ];
});

和我的AdministratorFactory.php

$factory - > define(App\ Administrator::class, function(Faker $faker) {
  return [
    'prn' => $faker - > unique() - > isbn10,
    'rfid_number' => $faker - > unique() - > isbn10,
    'first_name' => $faker - > firstName,
    'middle_name' => $faker - > lastName,
    'last_name' => $faker - > lastName,
    'role_id' => 1
  ];
});

我有UsersTableSeeder.php

public function run() {
  factory(App\ User::class, 50) - > create() - > each(function($user) {
    $user - > administrator() - > save(factory(App\ Administrator::class) - > make());
  });
}

每当我执行php artisan db:seed --class UsersTableSeeder时,user_id表格中的Administrator始终为0。我希望user_ididUser相同。他们都是1比1的关系。

1 个答案:

答案 0 :(得分:0)

尝试将管理员工厂的user_id覆盖为:

$user->administrator()->save(factory(App\ Administrator::class)->make(['user_id' => $user->id ]));