Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 如何使用EXTO更新或插入多行?(向上插入)_Postgresql_Elixir_Ecto - Fatal编程技术网

Postgresql 如何使用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

如何使用带Postgres的EXTO插入或更新具有不同值的多行

如果我有一个模式/结构:
%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一起使用

有更好的解决办法吗