Ecto 中的变量顺序

Variables in Ecto order by

我刚刚在学习 elixir,我不知道如何在 order by 语句中使用变量。我有两个变量 sortdirection。这是我正在处理的查询,我想按顺序替换 descdate。我试过 [^direction: entry.^sort] 但它抛出错误。有没有办法按顺序使用变量?

journal_entries = from entry in JournalEntry,
  preload: [
    :journal_entry_lines,
    journal_entry_lines: :journal_entry,
    journal_entry_lines: :chart_account
  ],
  where: entry.id in ^journal_entry_ids,
  order_by: [desc: entry.date],
  limit: 100,
  offset: 0

由于 keyword list 中的键是一个变量,因此您需要使用替代语法。

iex(1)> a = :desc
:desc
iex(2)> [{a, :b}]
[desc: :b]

您还需要使用 field/2 函数来动态访问字段名称。

以下内容应该有效

journal_entries = from entry in JournalEntry,
  preload: [
    :journal_entry_lines,
    journal_entry_lines: :journal_entry,
    journal_entry_lines: :chart_account
  ],
  where: entry.id in ^journal_entry_ids,
  order_by: [{^direction, field(entry, ^sort)}],
  limit: 100,
  offset: 0

这假定 direction 变量是 :asc:desc 之一,并且您的 sort 变量是架构中的一个字段。