luz*_*zny 28 elixir ecto phoenix-framework
如何在给定的ID列表中查找帖子?
这不起作用:
posts = Post |> where(id: [1, 2]) |> Repo.all
Run Code Online (Sandbox Code Playgroud)
Rails中的示例:
Post.where({ id: [1, 2]})
# SELECT * FROM posts WHERE id IN (1, 2)
Run Code Online (Sandbox Code Playgroud)
Gaz*_*ler 48
以下应该有效:
posts = Post |> where([p], p.id in [1, 2]) |> Repo.all
Run Code Online (Sandbox Code Playgroud)
den*_*lin 23
接受的答案给undefined function p/0了我,所以我来到这里:
from(p in Post, where: p.id in [1, 2]) |> Repo.all
Run Code Online (Sandbox Code Playgroud)
jnm*_*dal 11
其他海报既提供了所需的"关键字"和"表达式"模式,但我想评论并指出如果要从列表中插值,则需要^在变量之前使用运算符.在尝试其中任何一个之前,您还需要导入包含宏的模块(特殊因为宏具有不同的编译需求).这都是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)
Run Code Online (Sandbox Code Playgroud)