Doctrine2 - 限制返回关联实体

时间:2012-01-13 12:25:36

标签: php database doctrine-orm

是否可以限制从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();
   }
}

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

1 个答案:

答案 0 :(得分:2)

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

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

@OrderBy just sorts the fetched elements by one or more attributes的最后修改日期。 在集合上使用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