laravelのデータ入力にモデルファクトリを使用する

  • データテーブルを生成します(この場合、すべてのレッスンはデモンストレーションとして使用されます)。

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の職人の移行

  • モデルファクトリを使用してデータを作成する

    • モデルファクトリクラスファイルを作成する

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

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

  • シーダーファイルを生成

    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()转换为数组格式
    
  • データを入力

    当業者DB PHP:SEED
    PHP業者のDB:= LessonsTableSeeder SEED --class充填シーダー指定
    PHP業者移行を:フレッシュは、すべてのテーブルと再マイグレーションをすべて削除--seed、データベースを再構築するために使用することができます

元の記事を145件公開 38のような 17万人以上の訪問者

おすすめ

転載: blog.csdn.net/yehuaner33/article/details/104917209