【问题标题】:Ecto select relations from preloadEcto 从预加载中选择关系
【发布时间】:2017-04-01 01:23:19
【问题描述】:

我有一个查询可以在 json api 中使用关系。如果我排除 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)

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

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

    【讨论】:

    • 每个日记帐分录有很多日记帐分录行,如何防止重复?
    • 你真的没有。当您调用preload/3 时,它会执行单独的查询来加载该数据以防止重复。你可以走那条路并做多个查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多