【发布时间】:2022-01-05 02:06:52
【问题描述】:
我正在我的 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)
最好的方法是什么?
【问题讨论】:
-
不是你问的,但是......这是我经常使用 Elasticsearch 之类的东西的情况。它在搜索方面做得更好,并且 UNION 将不是问题。不过,如果您犹豫是否要为您的应用添加额外的技术,这完全可以理解。
标签: elixir union phoenix-framework ecto