Doctrine2-限制返回的关联实体


Doctrine2 - limit returned associated entities

是否可以限制从DB返回的关联数?例如,假设我有以下实体:

/** @Entity */
Article {
   /** @OneToMany(targetEntity="Comments") */
   private $comments; 
   ...
}
/** @Entity */
Comments { ... }

当迭代文章集时,我只想得到5条最近的评论。(总共可能有100个或更多)。我使用QueryBuilder从自定义存储库中获取集合。

在实践中,我会使用这样的东西:

$articles = $em->getRepository("Article")->findArticles($commentLimit, ...);
foreach($articles as $article) {
   foreach($article->getComments() as $comment) {
       //loop will iterate just $commentLimit times
       echo $comment->getText();
   }
}

是否可以在signle查询中执行此操作?

在这种特殊情况下,我会使用

/** @Entity */
Article {
   /**
    * @OneToMany(targetEntity="Comments", fetch="EXTRA_LAZY")
    * @OrderBy({"lastModified" = "DESC"})
    */
   private $comments; 
}

@OrderBy只是根据一个或多个属性对提取的元素进行排序,在这种情况下是根据它们最后修改的日期。在集合上使用EXTRA_LAZY会改变它们的行为,因为有些方法不会初始化整个集合,而只是初始化其中的一些部分。这是Doctrine'ORM'PersistentCollection#slice($start, $end)的情况,您可以在示例中使用它来加载第一个元素:

$articles = $em->getRepository("Article")->findArticles(...);
foreach($articles as $article) {
   foreach($article->getComments()->slice(0, $commentLimit) as $comment) {
       echo $comment->getText();
   }
}

如果你想做的是获取最后5条评论,而不管文章是什么,那么你应该使用DQL。