选择地图错误中的Ecto子查询

时间:2017-03-24 19:26:44

标签: elixir phoenix-framework ecto

我引用了这个问题(Ecto Model - subquery in select)来在我的select语句中创建一个子查询,但是我收到了这个错误。

  

预计会有一张地图:{%ZB.JournalEntry { meta :#Ecto.Schema.Metadata<:loaded,“journal_entries”>

这是我的代码,我错过了什么?如果我不使用select语句,代码就可以正常工作。

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
]

这是堆栈跟踪,但它似乎并不表示发生错误的行。

 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

我找到了另一种不会抛出错误的方法,但它没有组合这两个对象。

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

1 个答案:

答案 0 :(得分:0)

我能够以这种方式开展工作

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))
      },