这些是参数:
%{
"$select" => %{
"$avg" => ["arrive_at"],
"$count" => ["arrive_at"],
"$fields" => ["id"],
"$max" => ["cost"],
"$min" => ["arrive_at"],
"$sum" => ["arrive_at"]
}
}
这是代码:
select when is_map(select) ->
query = from(p in queryable, select: %{})
fields =
Enum.reduce(select, [], fn {key, value}, fields ->
Enum.reduce(value, query, fn {k, v}, query ->
case k do
"$avg" ->
val = Enum.at(v, 0)
query =
from(
p in query,
select_merge: %{avg: avg(field(p, ^String.to_atom(val)))}
)
"$count" ->
val = Enum.at(v, 0)
query =
from(
p in query,
select_merge: %{count: count(field(p, ^String.to_atom(val)))}
)
"$min" ->
val = Enum.at(v, 0)
query =
from(
p in query,
select_merge: %{min: min(field(p, ^String.to_atom(val)))}
)
"$max" ->
val = Enum.at(v, 0)
query =
from(
p in query,
select_merge: %{max: max(field(p, ^String.to_atom(val)))}
)
"$sum" ->
val = Enum.at(v, 0)
query =
from(
p in query,
select_merge: %{sum: sum(field(p, ^String.to_atom(val)))}
)
"$fields" ->
fields = Enum.at(v, 0)
IO.inspect(fields)
end
end)
end)
end
如果我在没有$fields
语句的情况下运行此代码。它正确返回选择合并查询。
但如果我用$fields
运行它。它给了我错误。
(Protocol.UndefinedError) protocol Ecto.Queryable not implemented for [:id]
它将$fields
的值作为我的模型名称并在查询中使用它
为什么它的表现如此?将$fields
的值作为我的模型。
非常感谢任何帮助。
感谢。
答案 0 :(得分:0)
您必须返回任何具有Ecto.Queryable
实施(即https://docs.silverstripe.org/en/3.1/developer_guides/files/image/)的内容,并且您的代码目前正在返回List
(fields
。)忘记你在reduce
里面,返回的值是累加器。 FWIW,
"$fields" ->
fields = Enum.at(v, 0)
IO.inspect(fields)
query # ⇐ NOTE THE RETURNED VALUE
将作为存根工作,直到正确实现。