Skip to content

生成测试数据

邱宇 edited this page Jun 4, 2018 · 1 revision

生成测试数据

创建表

migration 文件.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateDemoTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('demo', function (Blueprint $table) {
            $table->increments('id')->comment('ID');
            $table->string('name', 255)->default('')->comment('名称');
            $table->integer('age')->default(0)->comment('年龄');
            $table->text('description')->comment('描述');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('demo');
    }
}

建立 factory 文件.

➜  laravel-admin git:(dev) php artisan make:factory DemoFactory
Factory created successfully.
➜  laravel-admin git:(dev)

然后, 生成的文件目录是: /database/factories/DemoFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    return [
        //
    ];
});

改为:

<?php

use Faker\Generator as Faker;

$factory->define(App\Demo::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'age' => $faker->numberBetween(1, 99),
        'description' => $faker->text
    ];
});

运行 tinker, 生成测试数据.

➜  laravel-admin git:(dev) php artisan tinker
Psy Shell v0.9.5 (PHP 7.1.13 — cli) by Justin Hileman
>>> namespace App;
>>> factory(Demo::class, 2)->create();
=> Illuminate\Database\Eloquent\Collection {#2418
     all: [
       App\Demo {#2420
         name: "Miss Kayli Prosacco",
         age: 52,
         description: "Vitae et explicabo vero velit. Voluptatum distinctio asperiores quidem veritatis. Quae qui exercitationem consequatur officia est porro. Nemo veniam nam et asperiores aperiam rerum.",
         updated_at: "2018-06-04 04:15:07",
         created_at: "2018-06-04 04:15:07",
         id: 31,
       },
       App\Demo {#2421
         name: "Makenzie Pollich",
         age: 65,
         description: "Facilis ut voluptatem ex magnam culpa qui. Delectus et possimus eum et non.",
         updated_at: "2018-06-04 04:15:07",
         created_at: "2018-06-04 04:15:07",
         id: 32,
       },
     ],
   }
>>>

ok. 生成数据完毕.