mysql - 使用 Ecto (MySQL) 进行 upsert 的最简单方法是什么

标签 mysql elixir phoenix-framework ecto

执行更新插入在我的应用程序中很常见,我想实现最干净、最简单的方法来实现更新插入。

  1. 我应该使用片段来实现原生 sql upsert 吗?
  2. 有什么惯用的 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/

相关文章:

elixir - 为什么会出错——未定义的函数defstruct

multithreading - 我怎样才能拥有一个所有进程都可以访问的 map ?

web-services - Elixir - Simple Plug 示例在每次请求时两次调用调用方法

testing - Phoenix 框架 : What's the correct way to seed database for testing?

phoenix-framework - 如何在没有 javascript 的情况下从表单中修补或删除

mysql - codeigniter如何从mysql中的数据库自动增加记录

MySQL CREATE FUNCTION 语法

php - 对 SQL 表中的 2 列进行计数并分组

MySQL 从数据库中选择周范围

elixir - 在 Elixir 异常退出后,有没有办法重新启动具有不同配置的 GenServer?