laravel中批量填充假數(shù)據(jù)分為兩個(gè)部分
- 對(duì)要生成假數(shù)據(jù)的指定模型字段進(jìn)行賦值
- 批量生成假數(shù)據(jù)模型
使用artisan命令生成一個(gè)新的posts數(shù)據(jù)表進(jìn)行演示
php artisan make:migration create_posts_table --create=posts
在遷移文件中赃份,添加字段
Schema::create('posts', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('author', 50); $table->string('title', 100); $table->string('category')->default('laravel'); $table->text('content'); $table->timestamps(); $table->index('author'); });
執(zhí)行數(shù)據(jù)遷移命令,生成對(duì)應(yīng)的模型文件
php artisan migrate
php artisan make:model Post
在database/factories/ModelFactory.php
中對(duì)指定的字段進(jìn)行賦值
$factory->define(App\Post::class, function (Faker\Generator $faker) { $date_time = $faker->date(). ' ' . $faker->time(); return [ 'author' => $faker->name, 'title' => $faker->title, 'content' => $faker->text, 'created_at' => $date_time, 'updated_at' => $date_time, ]; });
生成對(duì)應(yīng)的seeder文件
php artisan make:seed PostsTableSeeder
在database/seeds/PostsTableSeeder.php
run()方法中寫(xiě)入生成假數(shù)據(jù)的代碼
$posts = factory(Post::class)->times(22)->make(); Post::insert($posts->toArray());
在database/seeds/DatabaseSeeder.php
run()方法中調(diào)用PostsTableSeeder類(lèi)
$this->call(PostsTableSeeder::class);
執(zhí)行生成數(shù)據(jù)的artisan命令
pjhp artisan db:seed