Ecto.Multi update/insert based on result of prior update/insert?

edit: i think i need Multi.merge for this, i missed it before. disregard this

f = fn(%{ :insert => result }) ->
  # how to do Multi.update/Repo.update here with a value in result while staying
  # within the context of the transaction?

  # this will perform the update on a new connection, outside the transaction, right?
  update = update_changeset(result)
  Repo.update(MyApp.Repo, update)
end

Multi.new()
  |> Multi.insert(:insert, changeset)
  |> Multi.run(:update, f)

Think of Multi.new() as an analogue to SQL BEGIN statement and Repo.transaction as an analogue to COMMIT statement. Every Repo.insert, update or delete called between these functions will run in a single transaction. If you’re in Phoenix environment, you can change log level to this

config :logger, level: :debug

for monitoring SQL queries generated by Ecto.

To access the results of previous operations, you should execute Repo insert/update/delete inside function provided to Multi.Run.

1 Like