Laravel Seeders

0 目的

建立好数据库以后,就是要建立测试数据看效果如何.

1 初体验

  1. 开始入门吧

    首先我是基于Eloquent开发的.

    1.1 添加ModelFactory

    ./database/factyories/ModelFactory.php里定义模拟数据

     $factory->define(App\Models\Institute_Model::class, function (Faker\Generator $faker) {
         return [
         'name' => $faker->name,
         ];
     });     
    

    $faker是一个模拟数据的框架,更多玩法

     //主要方法
     'code' => $faker->swiftBicNumber, //FCDNOFCFHST
     'name' => $faker->firstName, //Lynn
     'type' => $faker->numberBetween(0,3),
    

    1.2 添加Seeder,配置Model

     K:HapLab_Laravel maizhikun$ php artisan make:seeder User_Seeder
     Seeder created successfully.
    

    后会在./database/seeds创建一个User_Seeder文件

     class User_Seeder extends Seeder
     {
         public function run()
         {
             //
         }
     }
    

    然后在run()方法里配置上填充的Model数据

     public function run()
     {
         factory(App\Models\User_Model::class, 50)->create();
     }
    

    1.3 执行Seeder

     K:HapLab_Laravel maizhikun$ php artisan db:seed --class=User_Seeder
    

    note :或在./database/seeds/DatabaseSeeder里配置多个Seeder,然后执行’php artisan db:seed’

     class DatabaseSeeder extends Seeder
     {
         public function run()
         {
             Model::unguard();
    
             $this->call(User_Seeder::class);
    
             Model::reguard();
         }
     }   
    
  2. 玩一玩有外键的玩法

    基本和入门玩法一样,不过需要遍历循环主表

       public function run()
     {
         factory(App\Models\Institute_Model::class,21)->create()->each(function($institute){
             $institute->patients()->save(factory(App\Models\User_Model::class)->make());
         });
     }  
    
  3. 蜀黍,要是表中有多个外键怎么破.

    这时候就要到ModelFactory里修改了

     $factory->define(App\Models\Disease_Item_Type_Model::class, function (Faker\Generator $faker) {
         //获取外键可能的值,这里代码可以诱惑,用单例模式,不然每条数据都会获取一遍外键可的值.
         $id = get_all_id(new \App\Models\Disease_Type_Model());
         return [
             'disease_type_ID' => $faker->randomElement($id),
             'code' => $faker->swiftBicNumber,
             'name' => $faker->firstName,
         ];
     });
    

    上述代码中,get_all_id是获取外键的所有可能的值的方法.代码如下

     function get_all_id(\App\Models\Base_Model $base_Model){
         $model_datas = $base_Model->all();
         $model_id = array();
         foreach($model_datas as $model_data){
             array_push($model_id,$model_data['id']);
         }
         return $model_id;
     }   
    

其他问题

  1. 创建图片数据时,无法写目录,原因可能是路径问题,直接设定绝对路径即可

     //提示错误(Cannot write to directory "./Images"
     'url' => $faker->image(  '/Images','635','420')
    
     //改为
     'url' => $faker->image( base_path("public") . '/Images','635','420')
    

    虽然没报错,但是可能由于网络原因,增加极慢,弃之.

php

Comments