1. 安装
composer require fzaninotto/faker --dev
2. 创建 migrations
参考:laravel文档
3. 定义ModelFactory
说明:
- 默认是英文,如若需要支持中文,需要改写原来的做法
// 支持中文假数据
$faker = Faker\Factory::create('zh_CN');
$factory->define(ApiMeetTrue\Models\Lesson::class, function () use ($faker) { return [ 'title' => $faker->sentence, 'body' => $faker->paragraph, 'free' => $faker->boolean() ]; }); // 默认英文假数据 $factory->define(App\User::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name, 'email' => $faker->email, 'password' => bcrypt(str_random(10)), 'remember_token' => str_random(10), ]; });
4. 定义dbseeder
说明:
- 使用factory()
// LessonTableSeeder
<?php
use Illuminate\Database\Seeder; class LessonTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // params: Model, Number factory(ApiMeetTrue\Models\Lesson::class, 50)->create(); } }