Search code examples
elixirphoenix-frameworkecto

Ecto subquery in select map error


I referenced this question (Ecto Model - subquery in select) to create a subquery in my select statement but I get this error.

expected a map, got: {%ZB.JournalEntry{meta: #Ecto.Schema.Metadata<:loaded, "journal_entries">

Here is the code I have, am I missing something? If I leave off the select statement the code works fine.

journal_entries = from entry in JournalEntry,
  select: {
    entry,
    (fragment("(SELECT sum(amount) FROM journal_entry_lines WHERE kind = 0 and journal_entry_id = ?)", entry.id))
  },
  preload: [
    :journal_entry_lines,
    journal_entry_lines: :journal_entry,
    journal_entry_lines: :chart_account
  ],
  where: entry.id in ^journal_entry_ids and is_nil(entry.deleted_at),
  limit: ^per_page,
  offset: 0

sort = if not is_nil(params["sort"]) and params["sort"] in JournalEntry.sort_options,
  do: String.to_atom(params["sort"]),
  else: String.to_atom("date")

direction = if params["direction"] == "asc",
  do: :asc,
  else: :desc

journal_entries = from entry in journal_entries,
  order_by: [{^direction, field(entry, ^sort)}]

render conn, "index.json-api", data: Repo.all(journal_entries), opts: [
  include: "journal_entry",
  meta: meta_data
]

Here is the stack trace, but it doesn't seem to indicate the line the error happens on.

 web/controllers/journal_entry_controller.ex:1 ZB.JournalEntryController.action/2
 web/controllers/journal_entry_controller.ex:1 ZB.JournalEntryController.phoenix_controller_pipeline/2
 lib/zipbooks/endpoint.ex:1 ZB.Endpoint.instrument/4
 lib/phoenix/router.ex:261 ZB.Router.dispatch/2
 web/router.ex:1 ZB.Router.do_call/2
 lib/zipbooks/endpoint.ex:1 ZB.Endpoint.phoenix_pipeline/1
 lib/plug/debugger.ex:123 ZB.Endpoint."call (overridable 3)"/2
 lib/zipbooks/endpoint.ex:1 ZB.Endpoint.call/2

I found another way that doesn't throw an error but it doesn't combine the two objects.

select: %{entry: entry, amount: (fragment("(SELECT sum(amount) FROM journal_entry_lines WHERE kind = 0 and journal_entry_id = ?)", entry.id))},

Solution

  • I was able to get it work doing it this way

    journal_entries = from entry in JournalEntry,
          select: %{
            entry: entry,
            id: entry.id,
            account_id: entry.account_id,
            archived_at: entry.archived_at,
            date: entry.date,
            delete_at: entry.deleted_at,
            is_closing: entry.is_closing,
            is_confirmed: entry.is_confirmed,
            note: entry.note,
            amount: (fragment("(SELECT sum(amount) FROM journal_entry_lines WHERE kind = 0 and journal_entry_id = ?)", entry.id))
          },