从预载中选择关系

时间:2017-03-24 22:47:20

标签: elixir phoenix-framework ecto

我有一个查询,可以在json api中使用关系。如果我排除select语句它可以正常工作,但是,当我包含select语句时,关系不会显示。我需要select语句包含属性的子查询。如何在select中指定关系以便显示?

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,
    deleted_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))
  },
  preload: [
    :journal_entry_lines,
    journal_entry_lines: :journal_entry,
    journal_entry_lines: :chart_account
  ],
  where: entry.account_id == ^user.account_id
    and is_nil(entry.deleted_at)

1 个答案:

答案 0 :(得分:3)

使用select/3时,您无法以相同方式使用preload/3。您将不得不手动完成。

journal_entries = from entry in JournalEntry,
  # Make sure you join all of the tables you want data for.
  join: jel in assoc(entry, :journal_entry_lines,
  select: %{
    entry: entry,
    id: entry.id,
    account_id: entry.account_id,
    archived_at: entry.archived_at,
    date: entry.date,
    deleted_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)),
    # Specify a key for your relation, and set its value.
    journal_entry_lines: jel
  },
  where: entry.account_id == ^user.account_id
    and is_nil(entry.deleted_at)