1. 程式人生 > >Laravel中如何做數據庫遷移

Laravel中如何做數據庫遷移

con 重置 命令 int 參數 需要 void reverse func

總的來說,做一次獨立數據庫遷移只需要三步,分別是創建遷移文件、修改遷移文件、運行遷移

1.創建數據庫遷移文件
php artisan make:migration create_articles_table
1
然後在database/migrations 目錄下就會多出一個遷移文件,不過Laravel會在前面自動加上時間戳,來判斷執行順序
然後命令後面可以加上–table 或者 –create 來指定遷移文件對應的表名或者是新建一個數據表

php artisan make:migration create_articles_table --create=article
php artisan make:migration create_articles_table --table=article

1
2
2.修改遷移文件
打開新建文件我們會發現裏面包含了兩個方法up和down

當運行遷移時,調用up 方法
當回滾遷移時,調用down 方法

<?php

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

class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void

*/
public function up()
{
Schema::create(‘articles‘, function (Blueprint $table) {
$table->increments(‘id‘);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(‘articles‘);

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
我們主要修改up 方法,而Laravel已經為我們生成了兩個字段,我們在上面添加兩個字段

public function up()
{
Schema::create(‘articles‘, function (Blueprint $table) {
$table->increments(‘id‘);
$table->string(‘title‘);
$table->string(‘content‘);
$table->timestamps();
});
}
1
2
3
4
5
6
7
8
9
3.運行遷移
php artisan migrate
1
Laravel會自動尋找沒有執行的遷移文件,如果你只想執行指定文件的話,可以在後面加上–path參數,指定文件名

然後我們可以連接數據庫,看到新建了一張名為article的表,同時裏面包含了5個字段。


如果要回滾遷移的話
1.回滾所有遷移

php artisan migrate:reset
1
2.回滾最後一次執行的遷移

php artisan migrate:rollback
1
3.重置數據庫並重新運行所有遷移

php artisan migrate:refresh

Laravel中如何做數據庫遷移