本文給大家介紹的是Laravel5架構中最強大的功能之一資料庫遷移(database migrations),本文詳細給大家介紹資料庫遷移的步驟和方法,非常實用,有需要的小夥伴可以參考下。
database migrations 是laravel最強大的功能之一。資料庫遷移可以理解為資料庫的版本控制器。
在 database/migrations 目錄中包含兩個遷移檔案,一個建立使用者表,一個用於使用者密碼重設。
在遷移檔案中,up 方法用於建立資料表,down方法用於復原,也就是刪除資料表。
執行資料庫遷移
php artisan migrate#輸出Migration table created successfully.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_table
查看mysql資料庫,可以看到產生了三張表。 migratoins 表是遷移記錄表,users 和 pasword_resets。
如果設計有問題,執行資料庫復原
php artisan migrate:rollback#輸出Rolled back: 2014_10_12_100000_create_password_resets_tableRolled back: 2014_10_12_000000_create_users_table
再次查看mysql資料庫,就剩下 migrations 表了, users password_resets 被刪除了。
修改遷移檔案,再次執行遷移。
建立遷移
php artisan make:migration create_article_table --create='articles'#輸出Created Migration: 2015_03_28_050138_create_article_table
在 database/migrations 下產生了新的檔案。
<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateArticleTable 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'); }}
自動添加了 id列,自動成長,timestamps() 會自動產生 created_at 和 updated_at 兩個時間列。我們添加一些欄位:
public function up() { Schema::create('articles', function(Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamp('published_at'); $table->timestamps(); }); }
執行遷移:
php artisan migrate
現在有了新的資料表了。
假設我們需要添加一個新的欄位,你可以復原,然後修改遷移檔案,再次執行遷移,或者可以直接建立一個遷移檔案
php artisan make:migration add_excerpt_to_articels_table
查看新產生的遷移檔案
<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class AddExcerptToArticelsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // } /** * Reverse the migrations. * * @return void */ public function down() { // }}
只有空的 up 和 down 方法。我們可以手工添加代碼,或者我們讓laravel為我們產生基礎代碼。刪除這個檔案,重建遷移檔案,注意添加參數:
php artisan make:migration add_excerpt_to_articels_table --table='articles'
現在,up 方法裡面有了初始代碼。
public function up() { Schema::table('articles', function(Blueprint $table) { // }); }
添加實際的資料修改代碼:
public function up() { Schema::table('articles', function(Blueprint $table) { $table->text('excerpt')->nullable(); }); } public function down() { Schema::table('articles', function(Blueprint $table) { $table->dropColumn('excerpt'); }); }
nullable() 表示欄位也可以為空白。
再次執行遷移並檢查資料庫。
如果我們為了好玩,執行復原
php artisan migrate:rollback
excerpt 列沒有了。
以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!