慕容的工作随笔

慕容的工作随笔

记录学习和工作

【原创】Laravel中的数据库迁移

数据库迁移

默认迁移文件

  • database/migrations/2014_10_12_000000_create_users_table.php
  • database/migrations/2014_10_12_100000_create_password_resets_table.php
  • database/migrations/2019_08_19_000000_create_failed_jobs_table.php
  • database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php

迁移文件内容:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// users是表名
Schema::create('users', function (Blueprint $table) {
// bigIncrements() 的封装,此方法创建了一个 bigint unsigned 类型的自增长 id
$table->id();
$table->string('name');
// 由 string 方法创建了一个 email 字段,且在最后指定该字段的值为唯一值
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
// 为用户创建一个 remember_token 字段,用于保存『记住我』的相关信息
$table->rememberToken();
// 创建了一个 created_at 和一个 updated_at 字段,分别用于保存用户的创建时间和更新时间
$table->timestamps();
});
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists(&#039;users&#039;);
}

};

其中,运行迁移时 up 方法会被调用;回滚迁移时,down 方法会被调用。

回滚迁移

回滚迁移是迁移的逆操作,以下代码用来删除 users 表:

public function down()
{
    Schema::dropIfExists('users');
}

查看数据库

  • users是最重要的表,用户表;
  • migrations 表是执行 artisan migrate 命令时生成的,其作用是用来做迁移版本的记录;
  • password_resets是保存密码重置令牌的表;
  • personal_access_tokens API 令牌管理表;
  • failed_jobs 记录队列任务执行失败的表;

    其中 migrations 表中的 migration 字段表示迁移文件的名称,batch 字段用来记录迁移对应的批次,以此来实现 回滚迁移 的功能。

数据库回滚

php artisan migrate:rollback

评论 (0)

还没有评论,来做第一个吧。

发表评论

提交后需管理员审核通过后显示