2017-10-13 91 views
0

我在我的Phoenix应用程序的三个表上运行搜索功能,并且我想使用SQL的UNION运算符等方式加入它们。使用Ecto执行联盟

我有三个表:

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%" 

然而,外生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) 

这样做的最佳方法是什么?

+1

你问的不是什么,但...这是我经常使用类似的情况下, Elasticsearch。它在搜索方面做得更好,联盟也不会成为问题。完全可以理解,但如果您犹豫是否将额外的技术添加到您的应用程序中。 – cleaver

回答

1

Ecto doesn't support unions at the moment.直到外生增加了对工会的支持,最好的办法是使用原始的SQL与Repo.query/2

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