gpt4 book ai didi

elixir - 与 Ecto 执行联合

转载 作者:行者123 更新时间:2023-12-02 08:57:40 25 4
gpt4 key购买 nike

我正在 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 $1
UNION
SELECT title FROM posts WHERE title LIKE $1
UNION
SELECT name FROM categories WHERE name LIKE $1
""", ["%#{str}%"])

关于elixir - 与 Ecto 执行联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46720706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com