新闻中心

记录团队成长点滴以及对技术、理念的探索,同时我们乐于分享!

laravel用faker生成假数据

2020-09-25 09:20:14 分类:技术学堂

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


<?php


namespace App;


class Color extends \Eloquent {

    public $timestamps  = false;

}


2.创建一个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],

    ];

});

3.执行命令,生成假数据: 

DB::table('colors')->truncate();

factory(App\Color::class, 20) -> create();