本文根据 Devhints / Phoenix: Ecto migrations 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2020-02-23。
创建
$ mix ecto.gen.migration update_posts_table
creating priv/repo/migrations/20160602085927_update_posts_table.exs
···
$ mix ecto.migrate
$ mix ecto.rollback
创建迁移(不包含模型)。
创建模型
$ mix phoenix.gen.model Message messages user_id:integer content:text
此功能仅适用于 Phoenix 1.2 或更早版本;在 Phoenix 1.3 及更高版本中,不再提供模型功能。
创建上下文
$ mix phx.gen.context Images Album albums title:string subtitle:string privacy:string
迁移函数
创建数据表
create table(:documents) do
add :title, :string
add :title, :string, size: 40
add :title, :string, default: "Hello"
add :title, :string, default: fragment("now()")
add :title, :string, null: false
add :body, :text
add :age, :integer
add :price, :float
add :price, :float
add :price, :decimal, precision: 10, scale: 2
add :published_at, :utc_datetime
add :group_id, references(:groups)
add :object, :json
timestamps # inserted_at and updated_at
end
create_if_not_exists table(:documents) do: ... end
其他操作
alter table(:posts) do
add :summary, :text
modify :title, :text
remove :views
end
rename table(:posts), :title, to: :summary
rename table(:posts), to: table(:new_posts)
drop table(:documents)
drop_if_exists table(:documents)
table(:documents)
table(:weather, prefix: :north_america)
索引 (Indices)
create index(:posts, [:slug], concurrently: true)
create unique_index(:posts, [:slug])
drop index(:posts, [:name])
执行 SQL
execute "UPDATE posts SET published_at = NULL"
execute create: "posts", capped: true, size: 1024