Search code examples
elixirphoenix-frameworkecto

Insert or update data to the database in phoenix elixir


I have got this in my database:

[
  %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...}
]

Now when I add new data

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

I want to update the existing entry where posx AND posy are the same and add the two new count values. So my database should look like this:

[
  %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...}
]

If an entry entry where posx AND posy are the same doesnt exist I just want to insert a new entry to the database.

so how can I achieve this?


Solution

  • You should select and then either update or insert.

    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