laravel中使用模型工厂进行数据填充

  • 生成数据表(该案例中都使用lessons作为演示)

php artisan make:migration create_lessons_table

  • 修改表中字段属性

    • 在迁移文件中(如: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');
       }
    }
    
  • 执行数据库迁移

    php artisan migrate

  • 使用模型工厂创建数据

    • 创建模型工厂类文件

    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()
         ];
     });
    

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

  • 生成seeder文件

    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()转换为数组格式
    
  • 填充数据

    php artisan db:seed
    php artisan db:seed --class=LessonsTableSeeder 指定填充的seeder
    php artisan migrate:fresh --seed 删除所有的表并重新进行所有的迁移,可以用来重构数据库

发布了145 篇原创文章 · 获赞 38 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/yehuaner33/article/details/104917209
今日推荐