laravel 使用工厂函数填充数据,假数据的数量不一致
UserFactory
$factory->define(User::class, function (Faker $faker) {
$date_time = $faker->date . ' ' . $faker->time;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$6BixObQ108Da47eYT4RNa.SrgHIiL/8PI/roaj9JKlejscDyiXR0q', // password
'remember_token' => Str::random(10),
'created_at' => $date_time,
'updated_at' => $date_time,
];
});
ThreadFactory
$factory->define(Thread::class, function (Faker $faker) {
return [
//
'title' => $faker->sentence,
'body' => $faker->paragraph,
];
});
UserSeeder
$users = factory(User::class,5)->make();
$users->makeVisible(['password','remember_token']);
User::insert($users->toArray());
ThreadSeeder
$faker = app(Faker\Generator::class);
$user_ids = User::all()->pluck('id')->toArray();
$threads = factory(Thread::class,5)->make()->each(
function ($thread,$index) use ($user_ids,$faker){
$thread->user_id = $faker->randomElement($user_ids);
}
);
Thread::insert($threads->toArray());
数据库中user却有10条数据?
App\\User::all()->count(); // 10
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每次5条,seed执行两次就是10条