如果日期早于更新字段

时间:2020-06-16 07:31:21

标签: elixir ecto

我有一个简单的审核表:

schema "table" do
  field :unique_field, :string

  field :from_date, :naive_datetime
  field :to_date, :naive_datetime

  timestamps()
end

unique_field具有唯一的索引约束。

插入新条目时,如果发生冲突,如果新条目的from_date比当前条目旧,那么我想更新日期,否则保留旧日期。

当并行添加大量条目时,这必须起作用,这意味着应使用Repo.insert:on_conflict的组合。

1 个答案:

答案 0 :(得分:0)

您应该能够将Ecto.Query作为on_conflict的值。 in the Ecto documentation对此有更多描述。

没有测试它,但是类似的东西应该可以工作:

unique_value = 123 # Just as an example
new_from_date = ~D[2020-06-16] # Just as an example
update_query = 
  from(t in "table",
    where: t.unique_field == ^unique_value,
    where: t.from_date < ^new_from_date,
    update: [set: [from_date: ^new_from_date]]
  )

Repo.insert(..., on_conflict: update_query, conflict_target: :unique_field)
相关问题