Updated_at 在 Repo.update_all 之后的 Ecto

Updated_at in Ecto after Repo.update_all

我需要更新我的 Asset table 所以我需要做这样的事情。

from(a in Asset, 
where: a.id == ^asset.id, 
update: [set: [asset_name: "a name"] ]
)
|> Repo.update_all([])

这很好用,但是 updated_at 没有更新。

来自文档:

Keep in mind this update_all will not update autogenerated fields like the updated_at columns.

这是否意味着我需要将时间传递到我的查询中?像 DateTime.utc_now

谢谢

是的,您需要自动更新时间戳,因此它应该类似于:

Asset
|> where([a], a.id == ^asset.id)
|> update([set: [asset_name: "a name", updated_at: Timex.now()]])
|> Repo.update_all([])

我在这里使用 Timex.now(),但我想 DateTime.utc_now() 也能正常工作,但我还没有测试过。

如果您经常这样做,我可能会创建一个通用函数来接受查询并向其添加时间戳更新和 returns 更新的查询。