Laravel数据填充
2017-11-23 本文已影响0人
老王谈编程
框架:Laravel
版本:5.5.21
- 生成Factory
$ php artisan make:factory StudentsFactory
- 生成Seeder
$ php artisan make:seeder StudentsTableSeeder
- 填充Factory生成规则:database/factories/StudentFactory
$factory->define(Student::class, function (Faker $faker) {
$time = date('Y-m-d H:i:s');
return [
'name' => $faker->unique()->name,
'age' => rand(1,120),
'sex' => rand(0,2),
'created_at' => $time,
'updated_at' => $time,
];
});
- 填充Seeder数据:database/seeds/StudentsTableSeeder
public function run()
{
$students = factory(\App\Models\Student::class)->times(300)->make();
\App\Models\Student::insert($students->toArray());
}
- 添加Seeder到DatabaseSeeder:database/seeds/StudentsTableSeeder
public function run()
{
$this->call(StudentsTableSeeder::class);
}
- 运行数据填充命令,收工
$ php artisan db:seed --class=StudentsTableSeeder