我有Users
和UserProfiles
。
所有Users
只有一个UserProfile
。
我的UserTableSeeder
类正在创建25条记录,并为每条记录输出UserProfile
。
由于某种原因,我在Users
上获得的记录翻倍,并且在UserProfile
上指定的数量增加了,所以要插入50 Users
,要插入25 UserProfiles
。
种子:
public function run()
{
factory(App\User::class, 25)->create()->each(function ($user) {
$user->profile()->save(factory(App\UserProfile::class)->make());
});
}
用户类别:
class User extends Model
{
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
UserFactory:
$factory->define(User::class, function (Faker $faker) {
return [
'username' => $faker->userName(),
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
];
});
UserProfileFactory:
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'user_id' => factory('App\User'::class)->create()->id,
'bio' => $faker->paragraph()
];
});
UserProfile模型:
class UserProfile extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
由于所有用户都有个人资料,我的预期输出是25个用户和25个用户表
答案 0 :(得分:1)
更改此代码
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'user_id' => factory('App\User'::class)->create()->id,
'bio' => $faker->paragraph()
];
});
收件人
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'bio' => $faker->paragraph()
];
});