【问题标题】:Insert or update data to the database in phoenix elixir在 phoenix elixir 中向数据库插入或更新数据
【发布时间】:2020-09-19 22:11:41
【问题描述】:

我的数据库中有这个:

[
  %Element{id: 1, posx: 1, posy: 2, count1: 100, count2: 500, timestamps...},
  %Element{id: 2, posx: 2, posy: 2, count1: 150, count2: 450, timestamps...},
  %Element{id: 3, posx: 3, posy: 2, count1: 50, count2: 300, timestamps...}
]

现在当我添加新数据时

  Repo.insert{posx: 3, posy: 2, count1: 25 count2: 125}

我想更新 posx 和 posy 相同的现有条目并添加两个新的计数值。 所以我的数据库应该是这样的:

[
  %Element{id: 1, posx: 1, posy: 2, count1: 100, count2: 500, timestamps...},
  %Element{id: 2, posx: 2, posy: 2, count1: 150, count2: 450, timestamps...},
  %Element{id: 3, posx: 3, posy: 2, count1: 75, count2: 425, timestamps...}
]

如果不存在 posx 和 posy 相同的条目,我只想在数据库中插入一个新条目。

那么我该如何实现呢?

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    您应该选择然后更新或插入。

    q = from(Element, where: [posx: 3, posy: 2])
    case Repo.one(q) do
      nil -> 
        Repo.insert(...)
      %Element{count1: count1} = e -> 
        e = Ecto.Changeset.change(e, count1: count1 + 25)
        Repo.update(e)
    end
    

    【讨论】:

      【解决方案2】:

      它应该是 Repo.insert(struct_or_changeset, opts) 如文档https://hexdocs.pm/ecto/Ecto.Repo.html#c:insert/2中所述

      所以,试试这个

      Repo.insert(%Element{id: 3, posx: 3, posy: 2, count1: 25 count2: 125})
      

      如果要检查数据是否存在,如果存在则要更新,使用 on_conflict 选项。

      大概是这样的。

      # In Postgres (it requires the conflict target for updates):
      on_conflict = [set: [body: "updated"]]
      {:ok, updated} = Repo.insert(%Element{id: 3, posx: 3, posy: 2, count1: 25 count2: 125}, on_conflict: on_conflict, conflict_target: :id)
      
      # In MySQL (conflict target is not supported):
      on_conflict = [set: [title: "updated"]]
      {:ok, updated} = Repo.insert(%Element{posx: 3, posy: 2, count1: 25 count2: 125}, on_conflict: on_conflict)
      

      请参阅文档。

      【讨论】:

      • 这绝不是回答“我想更新 posx 和 posy 相同的现有条目并添加两个新的计数值..”
      猜你喜欢
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多