在elixir Exto中动态选择要更新的字段
似乎查询表达式中的更新只接受关键字列表()。那么,如何定义一个函数来动态选择要更新的列呢 大概是这样的:在elixir Exto中动态选择要更新的字段,elixir,ecto,Elixir,Ecto,似乎查询表达式中的更新只接受关键字列表()。那么,如何定义一个函数来动态选择要更新的列呢 大概是这样的: 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 我尝试了此操作,但在更新[{^column\u
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
我尝试了此操作,但在更新[{^column\u name,1}]中得到了格式不正确的:inc,需要一个关键字列表
我也尝试过使用figment/2
和field/2
,但没有成功。从中的示例来看,您似乎无法使用^
键,但您可以在整个关键字列表之前使用它,这将适用于您的用例
使用带有整数字段的计数器的型号计数器
:
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]
Thx,你救了我一天:)