如何将 Ecto.Adapters.SQL.query 与数组一起使用?
How to use Ecto.Adapters.SQL.query with Arrays?
我正在尝试使用 Ecto.Adapters.SQL.query
,它工作正常,但不适用于数组。例如,此语句失败:
Ecto.Adapters.SQL.query Repo, "SELECT p.* FROM posts p WHERE p.title in ()",
[["title1", "title2"]]
错误:
** (ArgumentError) Postgrex expected a binary that can be encoded/cast to
type "text", got ["title1", "title2"]. Please make sure the value you are
passing matches the definition in your table or in your query or convert
the value accordingly.
更新
没有简单的方法来做到这一点,但这不是 Ecto 的限制,它是 SQL 数据库/PostgreSQL 的限制, more details and workaround.
很难相信在 2016 年 SQL 数据库仍然缺乏这样的基本功能...
我认为这个问题的答案与您上一个问题的答案几乎相同。只需使用 here 中的 in
语法。
更新
要运行原始sql查询您的示例,您可以使用以下内容:
Ecto.Adapters.SQL.query(MyApp.Repo, "SELECT p.* FROM POSTS p WHERE p.TITLE IN (, )", ["title1", "title2"])
如果您使用的是 Postgres,您还可以使用 ANY
Ecto.Adapters.SQL.query(
Repo,
"SELECT p.* FROM posts p WHERE p.title = ANY()",
[["title1", "title2"]]
)
并且 Postgres 生成
我正在尝试使用 Ecto.Adapters.SQL.query
,它工作正常,但不适用于数组。例如,此语句失败:
Ecto.Adapters.SQL.query Repo, "SELECT p.* FROM posts p WHERE p.title in ()",
[["title1", "title2"]]
错误:
** (ArgumentError) Postgrex expected a binary that can be encoded/cast to
type "text", got ["title1", "title2"]. Please make sure the value you are
passing matches the definition in your table or in your query or convert
the value accordingly.
更新
没有简单的方法来做到这一点,但这不是 Ecto 的限制,它是 SQL 数据库/PostgreSQL 的限制, more details and workaround.
很难相信在 2016 年 SQL 数据库仍然缺乏这样的基本功能...
我认为这个问题的答案与您上一个问题的答案几乎相同。只需使用 here 中的 in
语法。
更新
要运行原始sql查询您的示例,您可以使用以下内容:
Ecto.Adapters.SQL.query(MyApp.Repo, "SELECT p.* FROM POSTS p WHERE p.TITLE IN (, )", ["title1", "title2"])
如果您使用的是 Postgres,您还可以使用 ANY
Ecto.Adapters.SQL.query(
Repo,
"SELECT p.* FROM posts p WHERE p.title = ANY()",
[["title1", "title2"]]
)
并且 Postgres 生成