Use model factory for data filling in laravel

  • Generate a data table (all lessons are used as a demonstration in this case)

php artisan make:migration create_lessons_table

  • Modify the field properties in the table

    • Add fields in the migration file (e.g. database / migrations / {time} _create_lessons_table.php)
    <?php
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateLessonsTable extends Migration
    {
       /**
        * Run the migrations.
        *
        * @return void
        */
       public function up()
       {
           Schema::create('lessons', function (Blueprint $table) {
               $table->id();
               $table->string('title');
               $table->text('body');
               $table->boolean('free');
               $table->timestamps();
           });
       }
    
       /**
        * Reverse the migrations.
        *
        * @return void
        */
       public function down()
       {
           Schema::dropIfExists('lessons');
       }
    }
    
  • Perform database migration

    php artisan migrate

  • Create data using a model factory

    • Create model factory class file

    php artisan make:factory LessonFactory

    <?php
    
     /** @var \Illuminate\Database\Eloquent\Factory $factory */
     
     use App\Models\Lesson;
     use Faker\Generator as Faker;
     
     $factory->define(Lesson::class, function (Faker $faker) {
         return [
             'title' => $faker->title,
             'body' => $faker->paragraph,
             'free' => $faker->boolean()
         ];
     });
    

    注:在上面一定要引入对应的模型文件

  • Generate Seeder file

    php artisan make:seeder LessonsTableSeeder

    <?php
    
      use Illuminate\Database\Seeder;
      use App\Models\Lesson;
      
      class LessonsTableSeeder extends Seeder
      {
          /**
           * Run the database seeds.
           *
           * @return void
           */
          public function run()
          {
              $lessons = factory(Lesson::class)->times(30)->make();
              Lesson::insert($lessons->toArray());
          }
      }
      // 执行数据填充的时候会运行run方法中的内容
      // times(个数)为要填充的数据个数
      // make()是生成数据
      // insert()中插入的数据格式必须是数组,所以用toArray()转换为数组格式
    
  • Data input

    Artisan db PHP: the SEED
    PHP Artisan db: = LessonsTableSeeder specify the SEED --class filled Seeder
    PHP Artisan the migrate: Fresh --seed delete all the tables and all of the re-migration, can be used to reconstruct the database

Published 145 original articles · Like 38 · Visits 170,000+

Guess you like

Origin blog.csdn.net/yehuaner33/article/details/104917209