美文网首页Laravel
laravel中批量填充假数据(一)

laravel中批量填充假数据(一)

作者: 游泳的茶 | 来源:发表于2017-06-25 15:35 被阅读0次
    laravel中批量填充假数据分为两个部分
    1. 对要生成假数据的指定模型字段进行赋值
    2. 批量生成假数据模型

    使用artisan命令生成一个新的posts数据表进行演示

    php artisan make:migration create_posts_table --create=posts

    在迁移文件中,添加字段
    Schema::create('posts', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('author', 50); $table->string('title', 100); $table->string('category')->default('laravel'); $table->text('content'); $table->timestamps(); $table->index('author'); });

    执行数据迁移命令,生成对应的模型文件

    php artisan migrate
    php artisan make:model Post

    database/factories/ModelFactory.php中对指定的字段进行赋值
    $factory->define(App\Post::class, function (Faker\Generator $faker) { $date_time = $faker->date(). ' ' . $faker->time(); return [ 'author' => $faker->name, 'title' => $faker->title, 'content' => $faker->text, 'created_at' => $date_time, 'updated_at' => $date_time, ]; });

    生成对应的seeder文件

    php artisan make:seed PostsTableSeeder

    database/seeds/PostsTableSeeder.phprun()方法中写入生成假数据的代码
    $posts = factory(Post::class)->times(22)->make(); Post::insert($posts->toArray());

    database/seeds/DatabaseSeeder.phprun()方法中调用PostsTableSeeder类
    $this->call(PostsTableSeeder::class);

    执行生成数据的artisan命令

    pjhp artisan db:seed

    假数据生成完成!!

    相关文章

      网友评论

        本文标题:laravel中批量填充假数据(一)

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