Skip to content

Zeroplex 生活隨筆

小 縮小字型大小。 中 重設字型大小。 大 放大字型大小。

Use FuelPHP oil Generate Model and Migration

Posted on 2012 年 11 月 14 日2021 年 3 月 12 日 By 日落 在〈Use FuelPHP oil Generate Model and Migration〉中尚無留言

FuelPHP 的 oil 提供快速建立 model 和 migration 的方法,例如要建立一資料表存放使用者帳號:

oil g model users id:int username:varvhar[100] email:varchar[200]

oil 則會幫你產生 table 的 migration:

<?php

namespace FuelMigrations;

class Create_users
{
   public function up()
   {
      DBUtil::create_table('users', array(
         'id' => array('constraint' => 11, 'type' => 'int'),
         'username' => array('constraint' => 100, 'type' => 'varvhar'),
         'email' => array('constraint' => 200, 'type' => 'varchar'),
         'created_at' => array('constraint' => 11, 'type' => 'int'),
         'updated_at' => array('constraint' => 11, 'type' => 'int'),

      ), array('id'));
   }

   public function down()
   {
      DBUtil::drop_table('users');
   }
}

其中 id 自動被當作 primary key,沒有設定 auto_increment。

若要建立一個資料表,需要有欄位「id」當作 primary key 且設定 auto_increment 屬性,可以將「id」從 oil 參數中去掉,當 oil 偵測到資料表沒有欄位名稱包含 id 且沒辦法設定 primary key 時,便會自動新增一個「id」的欄位:

   public function up()
   {
      DBUtil::create_table('users', array(
         'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true),
         'username' => array('constraint' => 100, 'type' => 'varchar'),
         'email' => array('constraint' => 200, 'type' => 'varchar'),
         'created_at' => array('constraint' => 11, 'type' => 'int'),
         'updated_at' => array('constraint' => 11, 'type' => 'int'),

      ), array('id'));
   }

oil 的參數中很清楚標示欄位的設定為 fieldname:type,沒辦法加入其他欄位屬性。假設要為欄位加上其他屬性,像是 null、index 等,則必須在 oil 產生 migration 以後,手動在 migration 中新增自己需要的屬性。

ps. oil 還會偵測資料表名稱,migration 會將資料表名稱改成複數。

Tags:FuelPHP, PHP

文章導覽

Previous Post: YouTube HD Suite on Chrome
Next Post: CodeIgniter 安裝與設定

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

其他

關於我  (About me)

小額贊助

  文章 RSS Feed

  留言 RSS Feed

Apache AWS Bash C/C++ Docker FreeBSD Git Google Java JavaScript Laravel Linux Microsoft MSSQL MySQL Nginx PHP PHPUnit PostgreSQL Python Qt Ubuntu Unix Vim Web Windows WordPress XD 作業系統 分享 好站推薦 專題 小提琴 攝影 新奇搞笑 新聞 旅遊 生活雜記 程式設計 網路架站 網頁設計 資訊學習 資訊安全 遊戲 音樂


創用 CC 授權條款
本著作係採用創用 CC 姓名標示-相同方式分享 4.0 國際 授權條款授權.

Go to mobile version