2017-03-24 17 views
0

我引用此問題(Ecto Model - subquery in select)在我的select語句中創建子查詢,但出現此錯誤。Ecto子查詢在選擇地圖錯誤

預期的地圖,有:{%ZB.JournalEntry {:#Ecto.Schema.Metadata <:加載, 「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))}, 
+0

你確定這條線拋出的錯誤?你能發佈周圍的代碼嗎? – Dogbert

+0

@Dogbert我加了周圍的代碼 –

+0

而這些行中的哪一行正是拋出那個錯誤?請在錯誤消息中張貼堆棧跟蹤。 – Dogbert

回答

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