doctrine querybuilder的限制和偏移量 [英] doctrine querybuilder limit and offset
问题描述
public function getHomeArticles($ offset = null,$ limit = null)
{
$ qb = $ this-> createQueryBuilder('a')
- > leftJoin('a.comments','c')
- > addSelect 'c')
- > addOrderBy('a.created','DESC');
if(false === is_null($ offset))
$ qb-> setFirstResult($ offset);
if(false === is_null($ limit))
$ qb-> setMaxResults($ limit);
return $ qb-> getQuery()
- > getResult();
}
所以在我的数据库中我有10篇文章。在我的BlogController中,我使用
$ blog = $ em-> getRepository('TestBlogBundle:Article')
- > getHomeArticles(3,4);
有了这个我想要4篇文章。但是作为回报我还有一篇文章。
有什么问题?
这是知道问题,其中 setFirstResult()
和 setMaxResults()
需要谨慎使用,如果您的查询包含一个fetch-joined集合。 / p>
正如关于第一个和最大结果项目:
如果您的查询包含指定结果的fetch-join集合
限制方法无法正常工作。设置最大结果
限制数据库结果行的数量,但是在
fetch加入集合的情况下,一个根实体可能会出现在许多行中,
有效地保持少于指定数量的结果
相反,您可以:
-
Lazy load
i'm a symfony beginner and i want to make a blog with the framework. i use repository to get home articles with this method :
public function getHomeArticles($offset = null, $limit = null)
{
$qb = $this->createQueryBuilder('a')
->leftJoin('a.comments', 'c')
->addSelect('c')
->addOrderBy('a.created', 'DESC');
if (false === is_null($offset))
$qb->setFirstResult($offset);
if (false === is_null($limit))
$qb->setMaxResults($limit);
return $qb->getQuery()
->getResult();
}
so in my database i have 10 articles. In my BlogController i use :
$blog = $em->getRepository('TestBlogBundle:Article')
->getHomeArticles(3,4);
With this i want 4 articles. But in return i also have one article.
What is the problem?
This is a know issue where setFirstResult()
and setMaxResults()
need to be use with care if your query contains a fetch-joined collection.
As stated about First and Max Result Items:
If your query contains a fetch-joined collection specifying the result limit methods are not working as you would expect. Set Max Results restricts the number of database result rows, however in the case of fetch-joined collections one root entity might appear in many rows, effectively hydrating less than the specified number of results.
Instead, you can:
Lazy load
use the Paginator (as stated by @Marco here)
这篇关于doctrine querybuilder的限制和偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!