运行 使用 Ecto 自定义 sql 查询

Run custom sql query with Ecto

我在玩 Elixir 和 Ecto 的东西。我想创建自定义 SQL 查询,它使用一些 postgres 特定的功能(在这种情况下:它搜索 postgres 数组)。

这是我正在尝试做的事情:

iex(5)> query = from g in MyModel, where: "'sample_tag' = ANY(tags)", select: g    #Ecto.Query<from g in MyModel, where: "'sample_tag' = ANY(tags)", select: g>
iex(6)> Repo.all(query)                                                        [debug] SELECT g0."id", g0."name", g0."description", g0."image_file_name", g0."image_file_size", g0."image_updated_at", g0."image_content_type" FROM "my_model" AS g0 WHERE ('''sample_tag'' = ANY(tags)') [] (0.9ms)

不幸的是,它正在被转义(所以它应该产生这样的东西:)

SELECT g0."id", g0."name", g0."description", g0."image_file_name", g0."image_file_size", g0."image_updated_at", g0."image_content_type" FROM "my_mode." AS g0 WHERE ('sample_tag' = ANY(tags))

我怎样才能做到这一点?

您可以使用 fragments 将表达式发送到数据库:

from g in MyModel,
  where: fragment("? = ANY(?)", "sample_tag", g.tags)

您可以 运行 sql 通过 Ecto 使用

Ecto.Adapters.SQL.query(Repo, "sql here")

还有第三个参数,用于准备语句。