如何在給定的ID列表中找到帖子?如何使用Ecto構建WHERE IN數組子句?
這不是工作:
posts = Post |> where(id: [1, 2]) |> Repo.all
例中的Rails:
Post.where({ id: [1, 2]})
# SELECT * FROM posts WHERE id IN (1, 2)
如何在給定的ID列表中找到帖子?如何使用Ecto構建WHERE IN數組子句?
這不是工作:
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
其他海報給出了需要的「關鍵字」和「表達式」模式,但我想評論並指出,如果要插入列表中的值,則需要在變量之前使用^
運算符。在嘗試其中之一之前,您還需要導入包含宏的模塊(特殊的,因爲宏有不同的編譯需求)。這是所有與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)
返回'undefined function p/0' –
@ denis.peplin,你必須'導入Ecto.Query'。 (不要忘了爲了執行'Repo.app',爲了保存'別名MyApp.Repo' – dcarneiro