来自预加载的 Ecto select 关系

Ecto select relations from preload

我有一个查询可以拉入要在 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)

当你使用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)