How to update Ecto field by using arithmetic

I have a case to update the field by adding the value from that field also. Is that possible to have one line syntax to this operation such as Repo.get(Product, product_id) |> Product.changeset(%{qty: :qty + 1]}) |> Repo.update

In this case you can use Repo.update_all/2

Product
|> where(id: ^product_id)
|> Repo.update_all(inc: [qty: 1])

In general case there are few ways:

  • Map.update!(map, :qty, & &1 + 1)
  • update_in(map, [:qty], & &1 + 1) if your structure implements Access
  • %{map | qty: map.qty + 1}
  • struct(struct, qty: struct.qty + 1) if this is a struct
2 Likes

Oh yes, this works

Product
|> where(id: ^product_id)
|> Repo.update_all(inc: [qty: 1])

Thanks @hauleth