Laravel 指定工厂/播种机创建双重记录
Laravel factory / seeder creating double records specified
我有 Users
和 UserProfiles
。
所有Users
有一个且只有一个UserProfile
。
我的 UserTableSeeder
class 正在创建 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:
class User extends Model
{
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
用户工厂:
$factory->define(User::class, function (Faker $faker) {
return [
'username' => $faker->userName(),
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => 'y$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
];
});
用户配置文件工厂:
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'user_id' => factory('App\User'::class)->create()->id,
'bio' => $faker->paragraph()
];
});
用户配置文件模型:
class UserProfile extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
我的预期输出是 25 个用户和 25 个用户 table 因为所有用户都有个人资料
更改此代码
$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()
];
});
我有 Users
和 UserProfiles
。
所有Users
有一个且只有一个UserProfile
。
我的 UserTableSeeder
class 正在创建 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:
class User extends Model
{
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
用户工厂:
$factory->define(User::class, function (Faker $faker) {
return [
'username' => $faker->userName(),
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => 'y$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
];
});
用户配置文件工厂:
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'user_id' => factory('App\User'::class)->create()->id,
'bio' => $faker->paragraph()
];
});
用户配置文件模型:
class UserProfile extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
我的预期输出是 25 个用户和 25 个用户 table 因为所有用户都有个人资料
更改此代码
$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()
];
});