[Intermediate Laravel] 9-Database-Seeding-and-Model-Factories

WBOY
Release: 2016-06-20 12:30:43
Original
1245 people have browsed it

简介

一般我们建立好应用时,需要插入一些简单数据,那我们该如何做,结论是运行Database-Seeding功能。

Database-Seeding 数据填充

默认 database\seeds\ 下只有单一的 DatabaseSeeder.php,我们新建 UsersTableSeeder.php 类:

class UsersTableSeeder extends Seeder{  /**   * Run the database seeds.   *   * @return void   */  public function run()  {    //不用factory,也可以使用App\User::create()或者DB::table()等    factory('App\User',50)->create();  }} 
Copy after login

修改 DatabaseSeeder.php :

class DatabaseSeeder extends Seeder{  /**   * Run the database seeds.   *   * @return void   */  public function run()  {    Model::unguard();    //调用UsersTableSeeder    $this->call('UsersTableSeeder');  }} 
Copy after login

执行 db:seed 命令: php artisan db:seed 随后我们可以查询数据是否插入:

  • 在 Unix 系统中,使用如下命令行: sqlite3 storage/database.sqlite select * from users;
  • 在 Windows 系统中可下载 Database4 免费版软件,打开 storage/database.sqlite 目录文件进行查看:

看到这里,你肯定会问这些人名,邮箱名是如何自动生成的,下面我们接着看。

数据规则

database\factories 目录下 ModelFactory.php 定义了 User 表中插入数据的规则定义:

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

UsersTableSeeder 中可以重写规则:

class UsersTableSeeder extends Seeder{  /**   * Run the database seeds.   *   * @return void   */  public function run()  {    //可以重写Model Factories中规则,统一插入 John Doe 的 name    factory('App\User',50)->create([      'name'  =>  'John Doe'    ]);  }} 
Copy after login

结果如下图:

我们可以在插入数据之前,删除无效数据:

class DatabaseSeeder extends Seeder{   protected $toTruncate = ['users'];   /**   * Run the database seeds.   *   * @return void   */  public function run()  {    Model::unguard();    // 循环删除表    foreach($this->toTruncateas $table)    {      DB::table($table)->truncate();    }     $this->call('UsersTableSeeder');  }} 
Copy after login

新建 LessonSeeder

这次我们同时建立 Model 和 Factories,运行命令行:

php artisan make:model Lesson --migration

补全 CreateLessonsTable 中属性字段:

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->text('body');      $table->timestamp('published_at');      $table->timestamps();    });  }   /**   * Reverse the migrations.   *   * @return void   */  public function down()  {    Schema::drop('lessons');  }} 
Copy after login

执行命令行: php artisan migrate ,创建 lessons 表结构。

补全 DatabaseSeeder 中调用 LessonsTableSeeder

class DatabaseSeeder extends Seeder{   protected $toTruncate = ['users'];   /**   * Run the database seeds.   *   * @return void   */  public function run()  {    Model::unguard();    // 循环删除表    foreach($this->toTruncateas $table)    {      DB::table($table)->truncate();    }     $this->call('UsersTableSeeder');    $this->call('LessonsTableSeeder');  }} 
Copy after login

执行命令行 php artisan db:seed 会出现如下图异常:

原因是:composer.json 中默认只加载了 database

解决方案有两种:

1. 运行命令行: composer dump-autoload

2. 利用命令行创建Seeder: php artisan make:seeder LessonsTableSeeder

插入数据

在 ModelFactory.php 中新增 Lesson 插入数据规则:

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

再执行命令行: php artisan db:seed ,OK,数据顺利插入,如下图:

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template