之前寫過一篇 Masonite migration 的文章,紀錄了新增表格的過程,這篇重點會放在異動既有的表格。

這裡的案例是在 transactions table 內新增 category 欄位,在開工之前插播一下我個人的命名慣例,如果框架或 ORM 沒有既有慣例的話,我個人的慣例是欄位名一律都使用英文單數,小寫,所以雖然 category 內容一定是多筆,但在這樣的命名慣例上,依然維持英文單數。

用 Masonite 的命令列工具產生 migration 檔:

$ craft migration add_category_column_to_transactions_table --table transactions

Created migration: 2019_10_11_133608_add_category_column_to_transactions_table.py

檔名的部份可以自行命名,沒有強制性的規則或約定,只要能清楚表達意思就可以。

把剛剛的檔案用編輯器打開,會長這樣:

from orator.migrations import Migration


class AddCategoryColumnToTransactionsTable(Migration):

    def up(self):
        """
        Run the migrations.
        """
        with self.schema.table('transactions') as table:
            pass

    def down(self):
        """
        Revert the migrations.
        """
        with self.schema.table('transactions') as table:
            pass

up() 區塊內加入新欄位的定義:

table.json('category')

完整的欄位型態可以參考 ORM 的文件

最後的 migration 檔案會長這樣:

from orator.migrations import Migration


class AddCategoryColumnToTransactionsTable(Migration):

    def up(self):
        """
        Run the migrations.
        """
        with self.schema.table('transactions') as table:
            table.json('category')

    def down(self):
        """
        Revert the migrations.
        """
        with self.schema.table('transactions') as table:
            pass

最後跑一下 craft migrate 就會把剛定義的欄位加入資料庫內了。