migration 簡介
Introduction
Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.
引用laravel官方對migration的唯一一段介紹纲缓,從第一句可以看出忿项,migration 是對數(shù)據(jù)庫(在咱們項目中就是mysql)的版本控制。好比git之于code,docker之于鏡像赞警,但migration不是laravel獨有的, YII2也有,python的主流框架中也有。
migration 相關(guān)使用
命令的使用建議還是看官方文檔托慨】拢總結(jié)了一下自己平時的使用習(xí)慣担钮。
舉個例子,比如現(xiàn)在需要在數(shù)據(jù)庫中新建一張支付訂單表
尤仍,并寫出對應(yīng)的Model類方法
步驟順序如下:
-
1 創(chuàng)建PayOrderModel類
在項目根目錄中運行命令
php artisan make:model Models\PayOrder -m
此命令做了兩件事情
1 創(chuàng)建了 PayOrder 類 (然后手動重命名為PayOrderModel,為了后續(xù)引用時不與service 和 controller 混亂)
2
-m
參數(shù) 指定生成遷移文件箫津。在database/migrations 文件中生成了遷移文件
2019_07_16_232149_create_pay_orders_table
-
2 生成支付訂單表
上一步中遷移文件的結(jié)構(gòu)如下
class CreatePayOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pay_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pay_orders');
}
}
可以看到,目前為止只運行了一個命令宰啦。model類建好了苏遥,數(shù)據(jù)庫的名字也已經(jīng)自動起好了,叫 pay_orders
,(系統(tǒng)自動加復(fù)數(shù))赡模,接下來編寫遷移文件田炭,編寫后的文件如下
class CreatePayOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pay_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('company_id')->comment('保險公司ID');
$table->integer('product_id')->comment('產(chǎn)品ID');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pay_orders');
}
}
然后運行
php artisan migrate:refresh -path database/migrations/2019_07_16_232149_create_pay_orders_table.php
會在數(shù)據(jù)庫中生成 pay_orders 表。
熟悉這個流程后漓柑,數(shù)據(jù)庫的回滾和填充后續(xù)參考官方文檔
migration 在小銘保的使用
小銘保1.0快速開發(fā)時诫肠,因為每個人在負(fù)責(zé)一個模塊司澎,而且時間比較緊急,migration沒有統(tǒng)一使用栋豫。
小銘保如果現(xiàn)在開啟migration ,可以開啟配置文件后挤安,運行
php artisan migrate:generate
生成線上數(shù)據(jù)庫表對應(yīng)的migration文件,相當(dāng)于sql 的一次 git init 操作
不過丧鸯,migration 終究只是輔助sql統(tǒng)一開發(fā)和線上管理的工具蛤铜,至于在小銘保以及后續(xù)其它laravel項目中的使用,大家可以討論一下丛肢,看看如何取舍