Masonite 與 Rails 相似,migration 把資料庫表格欄位都建立好後,還要再接著建立 model 才會在此專案內建立出真正屬於那個 table 的 class。

建立 model

以一個叫 transactions 的表格為例,只建立 model:

$ craft model Transaction

建立 model,並且也建立 seed 與 migration:

$ craft model Transaction -m -s transaction

上面這行指令相當於:

$ craft model Transaction
$ craft seed Transaction
$ craft migration create_transactions_tabel --create=transactions
  • Model 檔案在 app/Transaction.py。
  • Seed 檔案在 databases/seeds/transaction_table_seeder.py。
  • Migration 檔案在 databases/migrations/。

定義 model class

編輯後的 migratoin 檔案內容長這樣:

from orator.migrations import Migration


class CreateTransactionsTable(Migration):

    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create('transactions') as table:
            table.increments('id')
            table.integer('user_id').unsigned()
            table.foreign('user_id').references('id').on('users')
            table.date('date')
            table.integer('amount')
            table.string('receipt_number').nullable()
            table.string('description').nullable()
            table.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop('transactions')

Model 檔案內容長這樣:

"""Transaction Model."""

from config.database import Model

class Transaction(Model):
    """Transaction Model."""
    pass

空的,Masonite 不會自主幫我們加任何其它的敘述進去。

在加入映設定義前,先了解 Masonite 的約定

  • Model class 皆為單數名詞,頭文字大寫,如這裡的 Transaction。
  • Model class 映射的 table 講好就是複數名詞,都是小寫,如 transactions。

這就是 Masonite 與開發者之間的約定,因為約定成俗,所以在映射定義內,不用特別去指定 table,一切照約定行事:

Model ClassDatabase Table
Transactiontransactions

開始定義 model 關聯性:

"""Transaction Model."""

from config.database import Model
from orator.orm import belongs_to


class Transaction(Model):
    """Transaction Model."""

    @belongs_to('user_id', 'id')
    def user(self):
        from app.User import User
        return User
  • from orator.orm import belongs_to:引入 belongs_to() 修飾器待用。
  • def user(self) 這一整塊連同上面的 @belongs_to() 修飾器:定義 User class 與 Transaction class 兩者間的關聯。

最基本的 model 結構定義完畢。

參考資料