Ecto.Adapters.SQL.query(Repo, "Select * from table", [])
似乎执行查询并返回数据。有没有办法基于原始sql定义查询,以便可以作为参数传递给Repo.all()
?
我正在寻找类似的东西,
qry = Ecto.Adapters.SQL.query("select * from table", []) # This doesn't work
Repo.all(qry)
答案 0 :(得分:0)
你不能像这样将原始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"}]