close

 

 

首先確認目前的環境:

# php artisan env
Current application environment: local //目前為 local 環境

接著到 app/config/ 下 開啟 database.php 找到 default參數改為:

'default' => 'mysql',

再來先建立一個database名稱為 : myblog  的 資料庫。

然後將下面的Mysql後參數改為自己的資料庫配置([myblog]、username、password)

讓程式執行時能登入Mysql。

 

完成後執行

php artisan migrate:make create_posts_table  

成功會產生一個遷移檔案在 app/database/migrations 目錄下

前綴名稱會依日期而不同

開啟檔案裡面有一個繼承Migration 的 CreatePostsTable 類別

底下有兩個方法 : up 及 down

簡單來說,將要建立的資料寫入up方法中,執行後便可建立資料表及欄位

反之寫入down方法內,則會移除資料表以及欄位。

我們先試著寫入以下資料到up方法內:

Schema::create('posts', function($table){
$table->increments('id');
$table->string('title');
$table->string('content');
$table->timestamps();
});

建立一個 posts 的資料表

內有 [id] : increments (遞增並為主鍵(primary))

       [title] : 標題(字串)

       [content] : 內容 (字串)

       [timestamps] : 時間 

 

 

完成後執行

php artisan migrate

出現

Migration table created successfully.

即完成建立posts資料表。

(此處若產生 Access denied for user 'homestead'@'localhost'的提示,

請檢查 add/config/local/ 目錄下的database.php 配置是否正確)

 

Schema::drop('posts'); 

寫入 down 方法內

執行

php artisan migrate:rollback

即可移除此資料表。

 

 

參考來源:http://blog.tonycube.com/2015/01/laravel-8-migration-model.html

arrow
arrow

    CccKaAsS 發表在 痞客邦 留言(0) 人氣()