2016-09-13 64 views
0

Ecto.Adapters.SQL.query(Repo, "Select * from table", [])似乎执行查询并返回数据。有没有一种方法来定义基于原始sql的查询,以便它可以作为参数传递给Repo.all()将原始SQL查询作为参数传递给Repo.all()Ecto

我正在寻找类似的东西,

qry = Ecto.Adapters.SQL.query("select * from table", []) # This doesn't work 
Repo.all(qry) 
+0

您是否正在尝试创建'Ecto'不提供的高级SQL查询?例如, – TheAnh

+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"}]