Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine querybuilder limit and offset

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?

like image 571
Astram56 Avatar asked Feb 14 '13 21:02

Astram56


People also ask

Is Query Builder an ORM?

The ORM's query builder provides a simple to use fluent interface for creating and running queries.

What is Query Builder?

Query Builder is designed to enhance productivity and simplify SQL query building tasks. Query Builder provides a graphical user interface for creating SQL queries. You can drag-and-drop multiple tables, views and their columns onto a visual designer to generate SQL statements.

What is Query Builder in C#?

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird. sqlkata.com.

What is Query Builder in Java?

The query builder is a utility to generate CQL queries programmatically.


1 Answers

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()

like image 94
Mick Avatar answered Sep 22 '22 10:09

Mick