QueryBuilder Symfony2, 10 last results in ASC

10,973

From Doctrine's documentation:

15.2.3. Limiting the Result

To limit a result the query builder has some methods in common with the Query object which can be retrieved from EntityManager#createQuery().

    <?php
    // $qb instanceof QueryBuilder
    $offset = (int)$_GET['offset'];
    $limit = (int)$_GET['limit'];

    $qb->add('select', 'u')
       ->add('from', 'User u')
       ->add('orderBy', 'u.name ASC')
       ->setFirstResult( $offset )
       ->setMaxResults( $limit );

As you can see, you have to use setFirstResult() and setMaxResults().


I suggest you to look the chapter dealing about the QueryBuilder in order to avoid your ugly parameters concatenations...

Share:
10,973
Florian B
Author by

Florian B

Founder skulpy.com

Updated on June 28, 2022

Comments

  • Florian B
    Florian B almost 2 years

    My Query with QueryBuilder:

     <?php    $qb = $this->createQueryBuilder('m')  
                       ->join('m.sender', 's')
                       ->join('m.target', 't')
                                   ->addSelect('s')
                       ->addSelect('t')
                       ->where('(m.sender = '.$Myid.'OR m.target = '.$Myid.')')
                       ->andWhere('m.grouper ='.$groupe) 
                       ->orderBy('m.created_date', 'ASC')
                       ->setMaxResults('10');
    
                       return $qb->getQuery()
                       ->getResult();
    

    How to display the last 10 results in ASC? thank you