执行更新插入在我的应用程序中很常见,我想实现最干净、最简单的方法来实现更新插入。
- 我应该使用片段来实现原生 sql upsert 吗?
- 有什么惯用的 ecto 方法来做 upsert?
最佳答案
您可以使用 Ecto.Repo.insert_or_update/2 ,请注意,要使其正常工作,您必须从数据库中加载现有模型。
model = %Post{id: 'existing_id', ...}
MyRepo.insert_or_update changeset
# => {:error, "id already exists"}
例子:
result =
case MyRepo.get(Post, id) do
nil -> %Post{id: id} # Post not found, we build one
post -> post # Post exists, using it
end
|> Post.changeset(changes)
|> MyRepo.insert_or_update
case result do
{:ok, model} -> # Inserted or updated with success
{:error, changeset} -> # Something went wrong
end
关于mysql - 使用 Ecto (MySQL) 进行 upsert 的最简单方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37696035/