使用 Ecto,我如何构建一个 returns 结果出现在两个独立关联中的查询?
Using Ecto, how do I build a query that returns results that appear in two separate associations?
假设我有 3 个模式:标签、Post、用户。
Post 和带有连接 table 的标签之间存在多对多关系,Post 和带有连接 table 的用户之间存在多对多关系.
我想 select 属于给定标签和给定用户的帖子。
user_posts_query = user |> assoc(:posts)
tag_posts_query = tag |> assoc(:posts)
有什么方法可以组合这两个查询对象,并且在使用 Repo.all() 时仅从每个查询对象中获取重叠的结果?
我没有机会对其进行测试,但我认为这样的方法应该可行:
Post
|> join(:inner, [p], u in assoc(p, :users))
|> join(:inner, [p], t in assoc(p, :tags))
|> where([p, u, t], u.id == ^user.id and t.id == ^tag.id)
|> Repo.all()
它可能不是您要找的东西,但可能有用。
假设我有 3 个模式:标签、Post、用户。
Post 和带有连接 table 的标签之间存在多对多关系,Post 和带有连接 table 的用户之间存在多对多关系.
我想 select 属于给定标签和给定用户的帖子。
user_posts_query = user |> assoc(:posts)
tag_posts_query = tag |> assoc(:posts)
有什么方法可以组合这两个查询对象,并且在使用 Repo.all() 时仅从每个查询对象中获取重叠的结果?
我没有机会对其进行测试,但我认为这样的方法应该可行:
Post
|> join(:inner, [p], u in assoc(p, :users))
|> join(:inner, [p], t in assoc(p, :tags))
|> where([p, u, t], u.id == ^user.id and t.id == ^tag.id)
|> Repo.all()
它可能不是您要找的东西,但可能有用。