petspanda D
petspanda D

Reputation: 171

Insert or update on constraint in Ecto format

Below is the direct sql query,

insert into reports as rp (time_track, affiliate_manager_id)
values (#{time_track},#{revenue})
ON CONFLICT ON CONSTRAINT report_base_ids
  DO UPDATE SET revenue = 1

How it can be written in Ecto Elixir.

I Tried with

Report.upsert_by(:)

but it is not giving option to mention constraint

Upvotes: 0

Views: 1205

Answers (1)

Dogbert
Dogbert

Reputation: 222138

You can pass conflict_target: as {:constraint, constraint_name_as_atom} to Repo.insert or Repo.insert_all along with on_conflict: with the update instructions. Here's an example:

Repo.insert(
  Schema, # module
  %{foo: "bar"}, # data
  on_conflict: [set: [revenue: 1]],
  conflict_target: {:constraint, :report_base_ids}
)

You can read more about it in the documentation of Repo.insert, specifically the section on :on_conflict and :conflict_target.

Upvotes: 1

Related Questions