如何用 Ecto 构建 WHERE IN 数组子句?
How to build WHERE IN array clause with Ecto?
如何在给定的 ID 列表中查找帖子?
这不起作用:
posts = Post |> where(id: [1, 2]) |> Repo.all
Rails中的示例:
Post.where({ id: [1, 2]})
# SELECT * FROM posts WHERE id IN (1, 2)
以下应该有效:
posts = Post |> where([p], p.id in [1, 2]) |> Repo.all
接受的答案给了我 undefined function p/0
,所以我得出这个:
from(p in Post, where: p.id in [1, 2]) |> Repo.all
其他发帖人同时提供了 "keywords" 和 "expressions" 模式,但我想评论并指出,如果您从列表中插入值,则需要 ^
运算符在变量之前。在尝试其中任何一个之前,您还需要导入包含宏的模块(特殊是因为宏有不同的编译需求)。这都是 ecto 2.1.4,顺便说一句。所以:
import Ecto.Query
...
id_list = [1,2,4,5,6]
# "expressions"
Post
|> where([p], p.id in ^id_list)
# "keywords"
from(p in Post, where: p.id in ^id_list)
如何在给定的 ID 列表中查找帖子?
这不起作用:
posts = Post |> where(id: [1, 2]) |> Repo.all
Rails中的示例:
Post.where({ id: [1, 2]})
# SELECT * FROM posts WHERE id IN (1, 2)
以下应该有效:
posts = Post |> where([p], p.id in [1, 2]) |> Repo.all
接受的答案给了我 undefined function p/0
,所以我得出这个:
from(p in Post, where: p.id in [1, 2]) |> Repo.all
其他发帖人同时提供了 "keywords" 和 "expressions" 模式,但我想评论并指出,如果您从列表中插入值,则需要 ^
运算符在变量之前。在尝试其中任何一个之前,您还需要导入包含宏的模块(特殊是因为宏有不同的编译需求)。这都是 ecto 2.1.4,顺便说一句。所以:
import Ecto.Query
...
id_list = [1,2,4,5,6]
# "expressions"
Post
|> where([p], p.id in ^id_list)
# "keywords"
from(p in Post, where: p.id in ^id_list)