11

I’m playing with Elixir&Ecto stuff. I’d like to create custom SQL query, which uses some postgres–specific powers (in this case: it searches postgres array).

Here’s what I’m trying to do:

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)

unfortunaltely, it’s being escaped (so it should produce sth. like this: )

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))

How can I achieve that?

4

2 回答 2

18

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

from g in MyModel,
  where: fragment("? = ANY(?)", "sample_tag", g.tags)
于 2015-04-02T21:19:46.093 回答
6

您可以使用 Ecto 通过 Ecto 运行 sql

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

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

于 2015-04-02T22:19:50.963 回答