使用 Artisan CLI 的 migrate:make 命令建立遷移文件:
~~~
$ php artisan migrate:make create_articles_table --create=articles
~~~
遷移文件會建立在 app/database/migrations 目錄下,文件名會包含時間戳,用于在執行遷移時用來決定順序。
app/database/migrations/2014_09_03_084339_create_articles_table.php (你的遷移文件名可能有點不一樣)文件的內容如下所示:
~~~
<?php
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::drop('articles');
}
}
~~~
修改其中的創建代碼為:
~~~
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('text');
$table->timestamps();
});
~~~
在這個遷移中定義了一個名為 up 的方法,在運行遷移時執行。up 方法中定義的操作都是可以通過 down 方法實現可逆的,Laravel 知道如何撤銷這次遷移操作。運行遷移后,會創建 articles 表,以及一個字符串字段和文本字段。同時還會創建兩個時間戳字段,用來跟蹤記錄的創建時間和更新時間。
然后,使用 Artisan 命令運行遷移:
~~~
$ php artisan migrate
~~~
Laravel 會執行遷移操作,告訴你創建了 articles 表。
> Migration table created successfully. Migrated: 2014_09_03_084339_create_articles_table