乐趣区

关于laravel:从零开始学Laravel三数据迁移migration以及seed-factory批量生产测试数据

一. 数据库迁徙 migration

1. 输出以下命令,建设 migration 文件

php artisan make:migration create_admin_user_table --create=admin_user

这时会在 migrations 下生成带有日期的 migration php 文件,代码如下,这只是例子,能够依据具体情况批改

<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateAdminUserTable extends Migration
{
 /**
 * Run the migrations. * * @return void
 */ public function up()
 {Schema::create('admin_user', function (Blueprint $table) {$table->id();
 $table->string('username');
 $table->string('password');
 $table->string('email');
 $table->timestamps();});
 }
 /**
 * Reverse the migrations. * * @return void
 */ public function down()
 {Schema::dropIfExists('admin_user');
 }
}

2. 输出以下命令,进行数据库迁徙

docker exec dracohub_myapp_1 php artisan migrate

查看表构造如图,迁徙胜利

二.seed factory 工厂批量生产测试数据、

1. 输出以下命令,创立 seeder

php artisan make:seeder AdminUserTableSeeder

AdminUserTableSeeder.php

<?php
use AppModelsadminUser;
use IlluminateDatabaseSeeder;
class AdminUserTableSeeder extends Seeder
{
 /**
 * Run the database seeds. * * @return void
 */ public function run()
 {factory(adminUser::class,50)->create();}
}

2. 输出以下命令,创立 factory

php artisan make:factory adminUserFactory --model=adminUser

adminUserFactory.php

<?php
/** @var IlluminateDatabaseEloquentFactory $factory */
use FakerGenerator as Faker;
$factory->define(AppModelsadminUser::class, function (Faker $faker) {
 return [
 'username' => $faker->userName,
 'password' => $faker->password,
 'email' => $faker->email,
 'created_at' => $faker->dateTime('-1 years'),
 'updated_at' => $faker->dateTimeThisMonth,
 ];
});

3. 执行以下命令,插入测试数据

docker exec dracohub_myapp_1 php artisan db:seed --class=AdminUserTableSe
eder

如图,插入测试数据胜利

退出移动版