#Laravel 5.1 利用 Seeder 生成测试数据(范例)
php artisan make:model Lesson -m
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 生成指定的模型模拟数据