migration是一個命令列工具,功能很多,建立controller,middleware,資料庫建立表等等。
過程
整個過程是使用migration工具建立一個可執行檔php檔案,這個檔案裡面有修改資料庫的語句,然後執行這個可執行檔php檔案來寫入資料庫。
php artisan make:migration create_articles_table --create=articles
- --create是指定資料庫的表名字
- create_articles_table是用migration產生的可執行檔php檔案名稱字
產生的可執行檔例子如下:
database/migrations/XXXX.php
class CreateArticlesTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() //up代表建立資料庫方法 { Schema::create('articles', function (Blueprint $table) { //這裡用了create $table->increments('id');//這些是資料庫的欄位產生方法,詳細可以參考https://laravel.com/docs/5.2/migrations#creating-tables $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() //down代表刪除資料庫方法 { Schema::drop('articles'); //這裡可以看到使用drop,主要是為了復原或者清除資料庫使用的。 }}
執行 php artisan migration寫入資料庫
rollback復原資料庫
php artisan migrate::rollback復原上一次操作,rollback主要靠down方法和一個記錄復原操作的表來實現。
增加欄位
php artisan make:migration add_info_column_to_articles --table=articles
執行命令後會建立一個可執行檔php檔案,database/migrations/XXXX.php
class AddInfoColumnToArticles extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::table('articles', function (Blueprint $table) { //這裡寫入你需要增加的欄位即可 }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('articles', function (Blueprint $table) { //既然寫入了增加的欄位,然後這裡寫好這個欄位的對應的刪除方法,主要是為了以後刪除該欄位需要 }); }}
修改後再次執行 php artisan migration寫入資料庫
本文由 PeterYuan 創作,採用 署名-非商業性使用 2.5 中國大陸 進行許可。 轉載、引用前需聯絡作者,並署名作者且註明文章出處。神一樣的少年 » laravel migration基礎(資料庫)