gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:30:07 25 4
gpt4 key购买 nike

查询表达式中的更新似乎只接受关键字列表 ( 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/2 , 和 field/2 , 但没有运气。

最佳答案

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

使用带有整数字段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]

关于elixir - 动态选择要在 elixir ecto 中更新的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37718534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com