将原始 SQL 查询作为参数传递给 Ecto 中的 Repo.all()
Passing raw SQL query as an argument to Repo.all() in Ecto
Ecto.Adapters.SQL.query(Repo, "Select * from table", [])
似乎执行查询和 returns 数据。有没有一种方法可以定义基于原始 sql 的查询,以便它可以作为参数传递给 Repo.all()
?
我正在寻找类似的东西,
qry = Ecto.Adapters.SQL.query("select * from table", []) # This doesn't work
Repo.all(qry)
您不能像这样将原始 sql 传递给 Repo.all。
您能做的最好的事情就是将一些不受支持的数据库函数作为片段传递或找到解决方法。
#UNION ALL
iex(1)> result1 = Model1 |> select([m], m.title) |> Repo.all
["a", "b"]
iex(2)> result2 = Model2 |> select([m], m.title) |> Repo.all
["a", "c"]
iex(3)> result1 ++ result2
["a", "b", "a", "c"]
#UNION
iex(1)> result1 = Model1 |> select([m], m.title) |> Repo.all
["a", "b"]
iex(2)> result2 = Model2 |> select([m], m.title) |> Repo.all
["a", "c"]
iex(3)> (result1 ++ result2) |> Enum.uniq
["a", "b", "c"]
#UNION USING RAW SQL
iex(1)> query = "select title from models1 union select title from model2"
...
iex(2)> {:ok, %Postgrex.Result{columns: columns, rows: rows}} = Ecto.Adapters.SQL.query(Repo, query, [])
...
iex(3)> rows |> Enum.map(&Enum.zip(columns, &1)) |> Enum.map(&Enum.into(&1, %{}))
[%{"title" => "a"}, %{"title" => "b"}, %{"title" => "c"}]
Ecto.Adapters.SQL.query(Repo, "Select * from table", [])
似乎执行查询和 returns 数据。有没有一种方法可以定义基于原始 sql 的查询,以便它可以作为参数传递给 Repo.all()
?
我正在寻找类似的东西,
qry = Ecto.Adapters.SQL.query("select * from table", []) # This doesn't work
Repo.all(qry)
您不能像这样将原始 sql 传递给 Repo.all。
您能做的最好的事情就是将一些不受支持的数据库函数作为片段传递或找到解决方法。
#UNION ALL
iex(1)> result1 = Model1 |> select([m], m.title) |> Repo.all
["a", "b"]
iex(2)> result2 = Model2 |> select([m], m.title) |> Repo.all
["a", "c"]
iex(3)> result1 ++ result2
["a", "b", "a", "c"]
#UNION
iex(1)> result1 = Model1 |> select([m], m.title) |> Repo.all
["a", "b"]
iex(2)> result2 = Model2 |> select([m], m.title) |> Repo.all
["a", "c"]
iex(3)> (result1 ++ result2) |> Enum.uniq
["a", "b", "c"]
#UNION USING RAW SQL
iex(1)> query = "select title from models1 union select title from model2"
...
iex(2)> {:ok, %Postgrex.Result{columns: columns, rows: rows}} = Ecto.Adapters.SQL.query(Repo, query, [])
...
iex(3)> rows |> Enum.map(&Enum.zip(columns, &1)) |> Enum.map(&Enum.into(&1, %{}))
[%{"title" => "a"}, %{"title" => "b"}, %{"title" => "c"}]