与 Ecto 执行联合

Performing Unions with Ecto

我正在 运行我的 Phoenix 应用程序中的三个表上搜索功能,我想使用类似 SQL 的 UNION 运算符来加入它们。

我有三个表:

mix phx.gen.json Accounts User users handle:string email:string
mix phx.gen.json Content Post posts title:string content:string
mix phx.gen.json Content Category categories name:string

假设没有外键或链接表。

如果我想 运行 在 SQL 中搜索这些内容,我会这样做:

SELECT handle FROM users WHERE handle LIKE "%string%"
UNION
SELECT title FROM posts WHERE title LIKE "%string%"
UNION
SELECT name FROM categories WHERE name LIKE "%string%"

但是,Ecto 2 似乎不支持联合。我想做这样的事情:

query1 =
  from u in User,
    where: ilike(u.handle, ^"%#{str}%"),
    select: u

query2 =
  from p in Post,
    where: ilike(p.title, ^"%#{str}%"),
    select: p

query3 =
  from c in Category,
    where: ilike(c.name, ^"%#{str}%"),
    select: c

union = Ecto.SomethingLikeAUnion([query1, query2, query3])
result = Repo.all(union)

最好的方法是什么?

Ecto doesn't support unions at the moment. 在 Ecto 添加对联合的支持之前,最好的方法是使用原始 SQL 和 Repo.query/2:

MyApp.Repo.query("""
  SELECT handle FROM users WHERE handle LIKE 
  UNION
  SELECT title FROM posts WHERE title LIKE 
  UNION
  SELECT name FROM categories WHERE name LIKE 
""", ["%#{str}%"])

似乎添加了 UNION 和 UNION ALL here

并记录在案 here

supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, union: ^supplier_query