這篇文章將為大家詳細講解有關Laravel 5中怎么實現數據庫遷移,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
database migrations 是laravel最強大的功能之一。數據庫遷移可以理解為數據庫的版本控制器。
在 database/migrations 目錄中包含兩個遷移文件,一個建立用戶表,一個用于用戶密碼重置。
在遷移文件中,up 方法用于創建數據表,down方法用于回滾,也就是刪除數據表。
執行數據庫遷移
復制代碼 代碼如下:
php artisan migrate
#輸出
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 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_table
Rolled 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 下生成了新的文件。
<?php use 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
查看新產生的遷移文件
<?php use 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 列沒有了。
關于Laravel 5中怎么實現數據庫遷移就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。