【问题标题】:Doctrine 2.2 get max entity from associationDoctrine 2.2 从关联中获取最大实体
【发布时间】:2012-10-19 02:31:28
【问题描述】:

我正在编写一个类似论坛的小型应用程序(在 Symfony2 中),我遇到了以下问题:

我有两个实体:

class ForumThread {
  public $fourmThreadId;
  public $title;
  public $posts; // aggregation field -> ArrayCollection of ForumPost (can't be empty)
}

class ForumPost {
  public $content;
  public $timeCreated;
  public $thread; // aggregation field -> ForumThread (can't be null)
}

我现在想要获取所有论坛主题,仅包括每个主题的最新帖子。我想将它用于论坛概述:

-------------------------------------
| Thread                | Last Post |
-------------------------------------
| Name of Thread #1     |    ###    |
| Name of Thread #2     |    ###    |
| ...                   |    ...    |
-------------------------------------

我想获取完整的 ForumPost 实体,而不仅仅是单个字段(如时间戳)。

它还应该是高性能的:理想情况下在 1-2 个查询中(我在使用 INNER JOIN 的原始 SQL 中找到了一些东西,但我想要在 DQL 中或理想情况下使用 QueryBuilder - 我尝试从 SQL 到 DQL 的翻译没有成功) .

【问题讨论】:

    标签: doctrine-orm subquery


    【解决方案1】:

    好的,我找到了一个可行的解决方案,但不是最好的方法:

    $where = "fp.timeCreated = (SELECT MAX(fpi.timeCreated) FROM ApfelboxGuildBundle:ForumPost fpi WHERE fpi.thread = ft)";
    
    $query = $this->getRepository()->createQueryBuilder("ft")
            ->select("ft, fp")
            ->join("ft.posts", "fp")
            ->groupBy("ft.forumThreadId")
            ->addOrderBy("ft.isSticky", "desc")
            ->addOrderBy("fp.timeCreated", "desc")
            ->addOrderBy("ft.forumThreadId", "desc")
            ->setFirstResult($offset)
            ->setMaxResults(self::THREADS_PER_PAGE);
    

    注意WHERE 子句中的子查询。这可行,但有一个缺陷:它使用时间戳字段连接(以防止额外的嵌套子查询 - 在 DQL 中确实会产生解析错误),即使对于给定的线程,它也可能不是唯一的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      相关资源
      最近更新 更多