laravel faker使用(假数据填充)

1、前言

faker 是 laravel 默认就有的扩展,直接使用即可

#https://packagist.org/packages/fzaninotto/faker

composer require fzaninotto/faker

2、模型工厂

生成模型工厂

php artisan make:factory ArticleFakerFactory
#生成文件:database/factories/ArticleFakerFactory.php
<?php
use Faker\Generator as Faker;
$factory->define(\App\Model\Article\ArticleModel::class, function (Faker $faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->text($maxNbChars=2000),
        'creator' => $faker->name,
        'updater' => $faker->name,
        'created_at' => time(),
        'updated_at' => time()
    ];
});

3、seeder

生成seeder

php artisan make:seeder ArticleFakerSeeder
public function run()
{
	factory(\App\Model\Article\ArticleModel::class)
		->times(5)	//重复次数
		->make()	//创建模型集合
		->each(function ($model) {	//遍历模型实例
			$model->save();	//保存数据库
		});
}

执行 seeder

php artisan db:seed --class=ArticleFakerSeeder
上一篇:pyecharts的学习笔记7---DataZoomOpts


下一篇:02faker的使用