檢視原始碼 mix phx.gen.schema (Phoenix v1.7.14)

產生一個 Ecto schema 和 migration。

$ mix phx.gen.schema Blog.Post blog_posts title:string views:integer

第一個參數是 schema 模組,後接著它的複數名稱(用做資料表名稱)。

上面產生的 schema 會包含

  • lib/my_app/blog/post.ex 中的一個 schema 檔案,包含一個 blog_posts 資料表
  • 一個在存放庫中的 migration 檔案

產生的 migration 可以用 --no-migration 跳過。

情境

您的 schemas 可以產生並新增到一個分開的 OTP 應用程式。確認您的設定已經正確設定,或是用 CLI 中的 --context-app 選項手動指定情境應用程式。

通過設定

config :marketing_web, :generators, context_app: :marketing

通過 CLI

$ mix phx.gen.schema Blog.Post blog_posts title:string views:integer --context-app marketing

屬性

資源欄位用 name:type 語法給定,其中 type 是 Ecto 支援的類型。省略 type 會預設為 :string

$ mix phx.gen.schema Blog.Post blog_posts title views:integer

支援下列類型

  • :integer

  • :float

  • :decimal

  • :boolean

  • :map

  • :string

  • :array

  • :references

  • :text

  • :date

  • :time

  • :time_usec

  • :naive_datetime

  • :naive_datetime_usec

  • :utc_datetime

  • :utc_datetime_usec

  • :uuid

  • :binary

  • :enum

  • :datetime - :naive_datetime 的別名

此產生器也支援 references,我們會正確將給定的欄位與所引用的資料表的主鍵欄位關聯

$ mix phx.gen.schema Blog.Post blog_posts title user_id:references:users

這會在 migration 中產生一個 :integer 欄位 :user_id 並建立索引。

此外如果資料庫支援,也可以給定一個陣列類型,儘管它需要同時給定底層陣列元素的類型

$ mix phx.gen.schema Blog.Post blog_posts tags:array:string

可以用下面方式自動產生唯一欄位

$ mix phx.gen.schema Blog.Post blog_posts title:unique unique_int:integer:unique

可以用下面方式自動產生塗銷欄位

$ mix phx.gen.schema Accounts.Superhero superheroes secret_identity:redact password:string:redact

可以用下面方式產生 Ecto.Enum 欄位

$ mix phx.gen.schema Blog.Post blog_posts title status:enum:unpublished:published:deleted

如果沒有給資料類型,預設會是字串。

table

預設狀況下,migrations 和 schema 的資料表名稱會是資源提供的複數名稱。若要自訂這個值,可以提供 --table 選項。例如

$ mix phx.gen.schema Blog.Post posts --table cms_posts

二進制 id

產生的 migration 可使用 binary_id 來設定 schema 的主鍵及其參考,並搭配選項 --binary-id

儲存庫

產生的 migration 可使用 repo 來設定 migration 儲存庫資料夾,並搭配選項 --repo

$ mix phx.gen.schema Blog.Post posts --repo MyApp.Repo.Auth

migration_dir

產生的 migrations 可以加入特定的 --migration-dir,這會設定 migration 資料夾路徑

$ mix phx.gen.schema Blog.Post posts --migration-dir /path/to/directory

前綴

預設狀況下,migrations 和 schema 會在沒有前綴的情況下產生。

針對 PostgreSQL,這會設定「SCHEMA」(通常會透過 search_path 設定),而針對 MySQL,這會設定 migration 和 schema 所要產生的資料庫。前綴可於資料庫層面用於主題組織資料表。

可以使用 --prefix 標記指定前綴。例如

$ mix phx.gen.schema Blog.Post posts --prefix blog

警告

這個標記不會產生用於建立 schema/資料庫的 migrations。這必須手動進行或在個別的 migration 中進行。

預設選項

這個產生器使用應用程式 :generators 組態提供的預設選項。以下是預設值

config :your_app, :generators,
  migration: true,
  binary_id: false,
  timestamp_type: :naive_datetime,
  sample_binary_id: "11111111-1111-1111-1111-111111111111"

你可以透過提供對應的開關來覆寫每項呼叫的這些選項,例如 --no-binary-id 用於儘管預設組態如此,仍使用一般 id,或 --migration 用於強制產生 migration。

UTC 時間戳記

設定 :timestamp_type:utc_datetime,時間戳記會使用 UTC 時區建立。這會產生 DateTime 結構,而不是 NaiveDateTime。這也可以設定為 :utc_datetime_usec 以獲得微秒精度。