我认为在 Elixir 中有一个相对简单的 Ecto 查询,它抛出一个错误“协议(protocol)未实现”,我很困惑为什么。
所以这里是查询:
head_children_list = Comments
|> where([c], c.inserted_at in ^head_children)
|> Enum.sort_by(& &1["votetotal"])
所以 head_children 是一个列表,其中包含一个字符串时间戳值。这是确认的终端输出:
value of head_children
["2018-10-11 14:08:15.021033"]
所以我确实知道这是一个列表。但是,当我尝试执行上述查询时,我得到以下信息:
[info] Sent 500 in 168ms
[error] #PID<0.401.0> running AlbatrossWeb.Endpoint (cowboy_protocol) terminated
Server: localhost:4000 (http)
Request: POST /voteComment
** (exit) an exception was raised:
** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Query<from c in Albatross.Comments, where: c.inserted_at in ^[["2018-10-11 14:08:15.021033"]]>. This protocol is implemented for: DBConnection.PrepareStream, DBConnection.Stream, Date.Range, Ecto.Adapters.SQL.Stream, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Postgrex.Stream, Range, Stream
请注意,这表示协议(protocol)是为列表实现的。但这是一个列表!所以我很困惑。我试过使用 ^[head_children]
,它只是将它包装在另一个列表中,但这也失败并出现相同的错误。
有人知道这是怎么回事吗?
最佳答案
where(Comments, [c], c.inserted_at in ^head_children)
返回 %Ecto.Query{}
,它通过管道传输到 Enum。排序依据/2
。 %Ecto.Query{}
是一个结构而非列表,它不是Enumerable
。
你可能想要
head_children_list =
Comments
|> where([c], c.inserted_at in ^head_children)
|> Repo.all()
|> Enum.sort_by(& &1["votetotal"])
关于postgresql - Elixir Ecto 查询抛出 `Protocol not implemented Error`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52762692/