这已被问到这里如何使用 Ecto 的时间戳向现有表添加时间戳? https://stackoverflow.com/questions/35744390/how-to-add-timestamps-to-an-existing-table-with-ectos-timestamps,但是接受的解决方案意味着每个新条目都将具有相同的默认时间。我希望新条目具有正确的插入/更新时间。
eg.
# set default to given date to fill in all existing rows with timestamps
def change do
alter table(:my_table) do
timestamps(default: "2018-01-01 00:00:01")
end
end
如果这就是迁移的全部内容,every inserted_at
and updated_at
for :my_table
无论插入/更新的日期如何,都会将 2018-01-01 00:00:01 作为值。
我想做的是:
- 将日期时间添加到已存在行的 insert_at 和 Updated_at 列中。
-
inserted_at
and updated_at
应该null: false
就像向新创建的表添加时间戳时一样。
- 未来的条目应该具有正确的 Inserted_at 和 Updated_at 值,即 Inserted_at 是创建行的时间,Updated_at 是更改行的时间,而不是迁移中的默认设置。
我有几个解决方案可以实现这一目标,但它们看起来很混乱。我正在寻找是否有更干净的方法来执行此操作,或者是否有选项来处理我所缺少的这种情况。
工作移民1:
def up do
alter table(:my_table) do
timestamps(default: "now()")
end
execute("ALTER TABLE my_table ALTER COLUMN inserted_at SET DEFAULT now()")
execute("ALTER TABLE my_table ALTER COLUMN updated_at SET DEFAULT now()")
end
def down do
alter table(:my_table) do
remove :inserted_at
remove :updated_at
end
end
工作移民2:
def up do
alter table(:my_table) do
timestamps(null: true)
end
execute("UPDATE my_table SET inserted_at = now()")
execute("UPDATE my_table SET updated_at = now()")
alter table(:my_table) do
modify :inserted_at, :naive_datetime, null: false
modify :updated_at, :naive_datetime, null: false
end
end
def down do
alter table(:my_table) do
remove :inserted_at
remove :updated_at
end
end
您可以使用以下命令提供 SQL 函数作为默认值fragment https://hexdocs.pm/ecto_sql/Ecto.Migration.html#fragment/1。该文档提供了以下示例:
create table("posts") do
add :inserted_at, :naive_datetime, default: fragment("now()")
end
timestamps似乎转发default:选项add https://github.com/elixir-ecto/ecto_sql/blob/2e1378eb5d65c2f34d49b595891e7ab482b44507/lib/ecto/migration.ex#L962-L972,因此根据您的具体情况,您应该能够执行以下操作:
def change do
alter table(:my_table) do
timestamps(default: fragment("now()"))
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)