【问题标题】:Nested subqueries with Ecto使用 Ecto 的嵌套子查询
【发布时间】: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

usersposts 具有 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


    【解决方案1】:

    Subquerys are currently not allowed in where clauses; the documentation recommends using a JOIN instead. 您的查询可以很容易地转换为 JOIN。我尚未对其进行测试,但这应该可以:

    query =
      from f in Follow,
        where: f.following_id == 1,
        join: n in Newsfeeditem,
        on: n.user_id == f.follower_id,
        select: n
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多