【问题标题】:Run custom sql query with Ecto使用 Ecto 运行自定义 sql 查询
【发布时间】:2015-04-02 15:49:05
【问题描述】:

我在玩 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))

我怎样才能做到这一点?

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用 Ecto 运行 sql

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

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

      【讨论】:

      • +1 文档here。第三个参数是一个插值数组。文档中的示例展示得最好:iex&gt; Ecto.Adapters.SQL.query(MyRepo, "SELECT $1::integer + $2", [40, 2])%{rows: [{42}], num_rows: 1}
      • 为了更新,Ecto.Adapters.SQL 模块已移至ecto_sql 存储库,因此可以在here 找到更新的文档。
      猜你喜欢
      • 2019-10-29
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2021-02-14
      相关资源
      最近更新 更多