从零开始系列-Laravel编写api服务接口:4.Migration 和 Seed

Laravel框架
496
0
0
2022-04-12

简介

自动迁移是如今比较常用的功能,下面就用自动迁移部署本项目的所有表并用 seeder 初始化一些数据

直接贴代码

php artisan make:migration create_admins_table;
Schema::create('admins', function (Blueprint $table) {
    $table->id();
    $table->string('name')->comment('姓名');
    $table->string('account')->comment('登录账号');
    $table->string('password')->comment('登录密码');
    $table->timestamps();
});
\Illuminate\Support\Facades\DB::statement('ALTER table `admins` comment "管理员表"');
php artisan make:migration create_articles_table
Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->integer('user_id')->comment('哪个用户添加的');
    $table->integer('admin_id')->comment('哪个用户审核的');
    $table->string('title')->comment('文章标题');
    $table->text('content')->comment('文章内容');
    $table->tinyInteger('status')->default(0)->comment('0未审核1已审核');
    $table->timestamps();
});
\Illuminate\Support\Facades\DB::statement('ALTER table `articles` comment "文章表"');

运行php artisan migrate 命令

php artisan make:factory AdminFactory
public function definition()
{
  return ['name' => $this->faker->name,'account' => $this->faker->unique()->numberBetween(20000,50000),'password' => bcrypt('123456'), // password];
}
php artisan make:model Admin
# 在DatabaseSeeder.php里加入:
\App\Models\Admin::factory(10)->create();
执行seed
php artisan db:seed