【问题标题】:use dynamic values in map/2在 map/2 中使用动态值
【发布时间】:2018-01-01 10:44:10
【问题描述】:

所以我读到了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])

谢谢。

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

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

    Ecto.Query.API.map/2也可以用来动态选择字段:

    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。

    【讨论】:

      猜你喜欢
      • 2011-06-29
      • 1970-01-01
      • 2021-10-31
      • 2020-07-14
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多