美文网首页
laravel用faker生成假数据

laravel用faker生成假数据

作者: 苍老师的眼泪 | 来源:发表于2020-09-21 14:39 被阅读0次

天下武功,唯快不破。做事的时效性很重要,接下来介绍用laravel快速地生成假数据。

  1. 先创建一个model: App\Color.php
<?php

namespace App;

class Color extends \Eloquent {
    public $timestamps  = false;
}
  1. 创建一个Factory. database/factories目录里面有个参考的UserFactory.php,复制粘贴改成AnyName.php
<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Color;
use Faker\Generator as Faker;
use Illuminate\Support\Str;

use Faker\Provider\zh_CN\Color as Color_ZH;
use Faker\Provider\Color as Color_EN;


/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(Color::class, function (Faker $faker) {

    $n = mt_rand(1, 10);

    return [
        'zh' => Color_ZH::$safeColorNames[$n],
        'en' => Color_EN::$safeColorNames[$n],
    ];
});

  1. 执行如下命令,将生成20条假数据:
DB::table('colors')->truncate();
factory(App\Color::class, 20) -> create();

相关文章

网友评论

      本文标题:laravel用faker生成假数据

      本文链接:https://www.haomeiwen.com/subject/kmyvyktx.html