doctrine querybuilder的限制和偏移量 [英] doctrine querybuilder limit and offset

查看:121
本文介绍了doctrine querybuilder的限制和偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个symfony初学者,我想用框架做一个博客。我使用这个方法来获取主页文章:

  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('TestBlogBu​​ndle:Article')
- > getHomeArticles(3,4);

有了这个我想要4篇文章。但是作为回报我还有一篇文章。



有什么问题?

解决方案>

这是知道问题,其中 setFirstResult() setMaxResults()需要谨慎使用,如果您的查询包含一个fetch-joined集合。 / p>

正如关于第一个和最大结果项目


如果您的查询包含指定结果的fetch-join集合
限制方法无法正常工作。设置最大结果
限制数据库结果行的数量,但是在
fetch加入集合的情况下,一个根实体可能会出现在许多行中,
有效地保持少于指定数量的结果


相反,您可以:


  1. Lazy load


  2. 使用 Paginator (由@Marco here


  3. 使用 Doctrine\Common\Collections\Collection :: slice()



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:

  1. Lazy load

  2. use the Paginator (as stated by @Marco here)

  3. Use Doctrine\Common\Collections\Collection::slice()

这篇关于doctrine querybuilder的限制和偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆