Where I'm at
For this example, consider Friends.repo
Table Person
has fields :id
, :name
, :age
Example Ecto query:iex> from(x in Friends.Person, where: {x.id, x.age} in [{1,10}, {2, 20}, {1, 30}], select: [:name])
When I run this, I get relevant results. Something like:
[
%{name: "abc"},
%{name: "xyz"}
]
But when I try to interpolate the query it throws the error
iex> list = [{1,10}, {2, 20}, {1, 30}]
iex> from(x in Friends.Person, where: {x.id, x.age} in ^list, select: [:name])
** (Ecto.Query.CompileError) Tuples can only be used in comparisons with literal tuples of the same size
I'm assuming I need to do some sort of type casting on the list
variable. It is mentioned in the docs here : "When interpolating values, you may want to explicitly tell Ecto what is the expected type of the value being interpolated"
What I need
How do I achieve this for a complex type like this? How do I type cast for a "list of tuples, each of size 2"? Something like [{:integer, :integer}] doesn't seem to work.
If not the above, any alternatives for running a WHERE (col1, col2) in ((val1, val2), (val3, val4), ...)
type of query using Ecto Query?
2条答案
按热度按时间blpfk2vs1#
遗憾的是,应按照错误消息中的说明处理该错误:仅支持literal元组。
我无法想出更优雅、更不脆弱的解决方案,但我们总是把大锤作为最后的手段,其思想是生成并执行原始查询。
上面的语句应该在成功时返回
{:ok, %Postgrex.Result{}}
元组。pgvzfuti2#
您可以为每个字段使用一个单独的数组,并使用
unnest
将数组压缩为行,每个数组对应一列:另一种方法是使用json:
更新:我现在看到了标签mysql,上面的是为postgres写的,但也许它可以作为一个mySql版本的基础。