在 map/2 中使用动态值

use dynamic values in map/2

所以我了解了 Ecto.Query.API.map/2 函数,并且我有一个必须使用它的场景。

查询是这样的:

  from p in model,
    where: p.id == 1,
    select: map(p, [:id, :inserted_by, customer: [:id, :first_name]])

所以而不是硬编码的 idinserted_by 以及 idfirst_name。我想在这样的列表中使用动态值

  [:id, :inserted_by, :first_name]

我尝试通过将列表保存在变量中来使用 ^ 运算符。但它给出了错误 cannot use outside of match clause 如何更改动态值的查询? 像这样

  select: map(p, [^dynamic_value, customer: ^dynamic_value])

谢谢。

官方 Ecto 文档通过第二句话从字面上回答了这个问题:

Ecto.Query.API.map/2 can also be used to dynamically select fields:

fields = [:title, :body]
from p in Post, select: map(p, ^fields)

你的情况是:

dynamic_value = [:id, :inserted_by, customer: [:id, :first_name]]

from p in model,
where p.id == 1,
select: map(p, ^dynamic_value)

预先定义dynamic_value的问题是:from简而言之是一个宏,它内部有复杂的逻辑,它接受准备好的AST。