laravel 生成中文测试数据

  • Jesse
  • 2017-06-23 18:00:54
  • 438

在做开发是经常要添加一些测试数据,一个个添加未免效率低而且lower

好在别人已经造好轮子,使用faker生成测试数据

 

1.安装:

composer require fzaninotto/faker


2./database/factories/ModelFactory.php里编写数据填充类型

 

可以按照默认案例编写。

默认生成英文数据,如果要中文数据:

需设置:

 $faker = Faker\Factory::create('zh_CN');

 

例如:

$factory->define(App\Models\Job::class, function ($faker) {
    $faker = Faker\Factory::create('zh_CN');
    return [
        'job_name' => $faker->jobTitle,
        'pay_method' => $faker->numberBetween(1, 3),
        'salary' => $faker->numberBetween(10, 10000),
        'work_time' => $faker->dateTimeBetween('-12 months', 'now'),
        'work_address' => $faker->address,
        'work_desc' => $faker->catchPhrase,
        'company_name' => $faker->company,
        'username' => $faker->name,
        'phone' => $faker->phoneNumber,
        'longitude' => $faker->longitude(22, 40),
        'latitude' => $faker->latitude(114, 116),
        'created_at' => $faker->dateTimeBetween('-12 months', 'now'),
    ];
});

 

数据类型可以参考:https://github.com/fzaninotto/Faker

 

3.运行

在命令行模式下运行

php artisan tinker


然后运行:

factory(App\Models\Job::class,1000)->create();


就可以生成1000条测试数据了

需要注意的是:修改ModelFactory后,需要重新运行tinker