Postgresql 如何使用EXTO更新或插入多行?(向上插入)
如何使用带Postgres的EXTO插入或更新具有不同值的多行 如果我有一个模式/结构:Postgresql 如何使用EXTO更新或插入多行?(向上插入),postgresql,elixir,ecto,Postgresql,Elixir,Ecto,如何使用带Postgres的EXTO插入或更新具有不同值的多行 如果我有一个模式/结构:%Counter{key:String.t(),count:integer()} 如何插入或更新多个条目?如果记录不存在,我想插入它,但如果它存在,我想增加值 [ %{key: "questions:asked", count: 1}, %{key: "questions:answered", count: 1}, %{key: "ads:viewed", count: 3} ] exto.Re
%Counter{key:String.t(),count:integer()}
如何插入或更新多个条目?如果记录不存在,我想插入它,但如果它存在,我想增加值
[
%{key: "questions:asked", count: 1},
%{key: "questions:answered", count: 1},
%{key: "ads:viewed", count: 3}
]
exto.Repo.insert_all
with:on_replace看起来应该可以工作,但我希望每行都有唯一的值。您可以使用exto.Repo.insert_all
,但您必须提供查询并利用Postgresql在冲突操作中可用的excluded
表
upsert_query =
Counter
|> where([o], o.key == fragment("EXCLUDED.key"))
|> update(inc: [count: fragment("EXCLUDED.count")])
Repo.insert_all(Counter, records,
on_conflict: upsert_query,
conflict_target: [:key],
returning: false
)
排除的值是您传入的值,表示为仅在冲突中可用的临时表
应该注意的是,如果您希望设置特定值,可以将其与set而不是inc一起使用
有更好的解决办法吗