简介

迁移就像是数据库的版本控制器,通常配合 Laravel 的结构生成器,能更容易的生成应用程序的数据库结构。

在 Latavel 中尽量避免手动添加字段,使用数据库迁移能更容易修改和共享程序的数据库结构。


创建迁移

使用 Artisan 命令 make:migration 来创建迁移,新创建的迁移会放在 database/migrations 目录中,每个迁移的文件名都包含一个时间戳来确认迁移顺序

  1. php artisan make:migration create_users_table
  2. // 其中:
  3. // 数据表名:users

注意:

—table 和 —create 选项用「指定的迁移模板」预先填充指定的数据表:

php artisan make:migration create_users_table --create=users
php artisan make:migration add_votes_to_users_table --table=users

迁移结构

一个迁移类包含两个方法:up 和 down 。

UP 方法

用于新增数据库的数据表、字段或者索引的,

down 方法

应该与 up 方法的执行操作相反。

<?php

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

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}

执行迁移

执行 Artisan 的 migrate 命令 来执行所有未执行的迁移

php artisan migrate