Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yangwendaxia/343988a9450a8390480916b9eab2a5cf to your computer and use it in GitHub Desktop.
Save Yangwendaxia/343988a9450a8390480916b9eab2a5cf to your computer and use it in GitHub Desktop.

#Laravel 5.1 利用 Seeder 生成测试数据(范例)

1. 生成 Model 文件及数据表定义文件

    php artisan make:model Lesson -m

2. 定义数据表,生成数据库表

    
class CreateLessonsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('lessons', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('intro');
            $table->timestamp('published_at');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('lessons');
    }
}
php artisan migrate

##3. 生成 seeder 文件

php artisan make:seeder LessonsTableSeeder

##4. 编辑 LessonsTableSeeder Run() 方法,为生成测试数据做准备

class LessonsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(Lesson::class,50)->create();
    }
}

##5. 在 DatabaseSeeder.php Run() 方法里添加上面的 seeder

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     * @return void
     */
    public function run()
    {
        Model::unguard();

        DB::table('users')->truncate();
        $this->call(UsersTableSeeder::class);
        $this->call(LessonsTableSeeder::class);
        Model::reguard();
    }
}

##6. 在 ModelFactory.php 中添加定义 Lesson 模型的生成细节

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\User::class, function ($faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => str_random(10),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Lesson::class, function ($faker) {
    return [
        'title' => $faker->sentence,
        'intro' => $faker->paragraph,
        'published_at' => $faker->dateTime,
    ];
});

##7. 运行模拟数据生成

php artisan db:seed

php artisan db:seed --class=LessonsTableSeeder 生成指定的模型模拟数据

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment