动态选择要在 elixir ecto 中更新的字段

Dynamically choose field to update in elixir ecto

查询表达式中的更新似乎只接受关键字列表(escape/3 in Ecto.Query.Builder.Update)。那么如何定义一个函数来动态选择要更新的列?

像这样:

def increment_field(column_name, count) when is_atom(field) do
     from t in Example.Entity, where: field(t, ^column_name) >= 0, update: [inc: [{^column_name, 1}]]
end

我试过这个但是得到了 malformed :inc in update [{^column_name, 1}], expected a keyword list

我也尝试过使用 figment/2field/2,但没有成功。

Ecto.Query.Builder.Update.escape/3 中的示例来看,您似乎不能将 ^ 与关键字一起使用,但您 可以 在整个关键字列表之前使用它,这将适用于您的用例。

模型 Counter 具有整数字段 counter:

iex(1)> from(c in Counter, select: c.counter) |> Repo.all
[16, 2, -93]
iex(2)> field = :counter
:counter
iex(3)> from(c in Counter, update: [inc: ^[{field, 1}]]) |> Repo.update_all([])
[debug] UPDATE "counters" SET "counter" = "counter" + ? [1] OK query=2.5ms
{3, nil}
iex(4)> from(c in Counter, select: c.counter) |> Repo.all
[17, 3, -92]