将sql查询转换为ecto查询

问题描述 投票:0回答:1

我有一个如下的SQL查询

select username, email, nickname, lastname, firstname, phone 
 from a
 where NOT EXISTS
 (
 select b.tip_team_id from b
 where b.season_id = 1
 and b.round_id = 2
 and a.id = b.user_id
 );

我想将其转换为Ecto查询...有人可以帮我吗?

elixir ecto
1个回答
0
投票

您可以通过使用基础适配器来运行原始SQL查询,例如。

query = """
  select username, email, nickname, lastname, firstname, phone 
  from a
  where NOT EXISTS
  (
    select b.tip_team_id from b
    where b.season_id = $1::integer
    and b.round_id = $2::integer
    and a.id = b.user_id
  )
"""

Ecto.Adapters.SQL.query!(MyApp.Repo, query, [1, 2])

请注意,Ecto.Adapters.SQL.query!/3函数将使用有序参数的列表替换到您的查询中(以便列表中的第一项替换查询中的$1,第二项替换为$2,依此类推)。为了使它起作用,您需要传递您在指定use Ecto.Repo(在上面的示例中为MyApp.Repo)的已定义Ecto Repo模块。另请注意,如果您要替换的值不是整数,则可以省略::integer

返回的结果将是%Postgrex.Result{}结构,例如

%Postgrex.Result{
   columns: ["username", "email", "nickname", "lastname", "firstname", "phone"],
   command: :select,
   connection_id: 327,
   messages: [],
   num_rows: 1,
   rows: [["admin", "admin@email", "Big Guy", "Jones", "Boss", "888-555-1212"]]
 }

因此,您必须进行一些模式匹配才能从该结构中获取rows的列表。

有时,像这样简单地使用原始查询比花时间定义Ecto Schema模块要容易得多-确实由您和您的用例决定,但是根据情况和您的偏好,您可能希望在为数据库中的每个表定义Ecto模式的“标准”方式。

© www.soinside.com 2019 - 2024. All rights reserved.