Laravel Database Migrations
PHP:7.2
Laravel:5.7
Laravel 提供了一個 DB Migration 的功能,可以快速管理、產生專案的資料庫,適合用在測試或一些較小型的專案部署上。
Generating Migrations
在開始之前,必須先描述好 DB 的型態、欄位等等資訊,因此需要先產生 Migration File 來紀錄 DB 的資訊。
透過 artisan make:migration <file_name> 就可以直接產生 Migration File:
php artisan make:migration create_member_table
artisan 會自動產生以 時間 + 檔名命名,而且已經寫好基本的 DB 設定的檔案,並存放在 database/migrations。
以下為自動產生出來檔案內容,註解已經說明很清楚,當執行 migration 後會根據 up() 描述管理 DB,而 down() 就是還原時所執行的 method。
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMemberTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('member', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('member');
}
}
在利用 artisan 產生 Migration File 時,artisan 會根據 create_<table_name>_table 這樣的 pattern 在 up() 與 down() 的 method 裡自動產生建立 table 的設定。因此,如果你的檔名不是這種 pattern 的話,會得到兩個空的 method。
當然,這樣子的限制並不是絕對,只是讓開發者方便使用而已,如果真的不想用這樣子的命名方式也是可以使用的。
// 與 create_member_table 建出來的檔案相同
php artisan make:migration member --create=member
// 會產生 Schema::table 的設定,用於修改資料表
php artisan make:migration member --table=member
Running Migrations
Notice: 操作 migrate 需要先設定好 DB 設定,確定資料庫連線之後才能操作。
執行 migrate
php artisan migrate
順利執行以後,資料庫中除了出現原本設定 member 的 table,同時也出現了一張 migrations 的 table。migrations 會用來紀錄你的 Migration File 及批次(batch)的紀錄。
在 migrate member 之後,如果再產生一個新的 Migration File,並執行,那系統會針對沒有 migrate 過的檔案做處理,而第二次 migrate 的檔案,在 migrations table 的批次(batch) 就會變成 2。
範例
php artisan make:migration create_product_table
php artisan migrate
還原上一次的 migrate
# 針對最後一個批次進行還原
php artisan migrate:rollback
查看 migrate 狀態
php artisan migrate:status
全數 reset
php artisan migrate:reset
Migration Structure
在說明完如何執行 migrate 之後,接下來介紹一下如何撰寫 Migration File 中 DB 的設定。
Create table 範例
Schema::create('member', function (Blueprint $table) {
$table->increments('id'); // 建立 increments key
$table->integer('label_id'); // 設定 Ingeger
$table->string('name', 70); // 設定字串及長度
$table->tinyInteger('is_enabled')->default(1); // 設定 tinyInteger 及預設值
$table->timestamps(); // 建立 created_at and updated_at
$table->unique(['label_id', 'name'], 'key_name'); // 設定 Unique key
$table->index(['isbn'], '__btree_isbn'); // 設定 Index
$table->index([\Illuminate\Support\Facades\DB::raw('isbn(5)')], '__btree_isbn'); 設定特定長度的 Index
});
Notice: 如果需要透過 migrate 修改 column,必須再多 require 一個
dbal套件
composer require doctrine/dbal
Update table 範例
Schema::table('member', function (Blueprint $table) {
$table->string('name', 20)->change(); // 修改 name 欄位的長度
$table->string('email', 50)->after('name'); // 新增 email 欄位在 name 之後
$table->renameColumn('is_enabled', 'status'); // 修改欄位名稱
});
其他細節可以參考官網文件:migrations