【发布时间】:2017-10-13 06:36:43
【问题描述】:
使用 Ecto v2.2.6、Phoenix 1.3
我有一个带有新闻源的博客应用程序。它的工作原理是这样的:
- 用户可以提交帖子。
- 用户可以关注其他用户。
- 当用户提交帖子时,会在 Newsfeed 表中添加一个项目。
- 用户可以看到他们关注的用户提交的帖子的新闻源。
我想使用 Ecto.Query 从给定用户关注的用户那里获取新闻源项目列表。
快速背景。以下是对象:
用户
mix phx.gen.json Accounts User users email:string password:string
发布
mix phx.gen.json Content Post posts title:string content:string user_id:references:users
(users 和 posts 具有 has_many: 和 belongs_to: 关系。)
关注
mix phx.gen.json Accounts Follow follows following_id:references:users followed_id:references:users
(当用户 A 关注用户 B 时,会创建一个新的 Follow 条目,其中 following_id 指向 A,followed_id 指向 B。)
新闻源
mix phx.gen.json Content Newsfeeditem newsfeeditems type:string, user_id:integer, content:string
现在我想查询这些东西。对我来说,获取给定用户的Newsfeeditems 列表很简单:
导入 Ecto.Query
query =
from n in Newsfeeditem,
where: n.user_id == ^user_id
假设我是用户 1,我正在关注用户 2、3 和 4。follows 表中有三个条目。要获取这些用户的所有相应新闻提要项,查询应如下所示:
query =
from n in Newsfeeditem,
where: n.user1_id in [2,3,4]
我想让它动态化。这就是我迷路的地方。我想做类似这样的事情:
subquery =
from f in Follow,
where: f.following_id == 1,
select: f.follower_id
query =
from n in Newsfeeditem,
where: n.user_id in (Repo.all(subquery))
显然这不起作用,但我不确定如何正确构建这些东西。
如何通过子查询选择它? (注意我正在寻找专门的子查询解决方案,但如果有更好的方法加分)
【问题讨论】:
标签: elixir phoenix-framework ecto