Search code examples
symfonydoctrinesubquerylimitdql

Subquery's with limit in Doctrine/Symfony using DQL


I would like to know how can I set limit on 1 query and then query based on the selected results.

For example I want to select the last 100 posts and the do some operation.

$first_query= $this->getEntityManager()
    ->createQuery(
        'SELECT p FROM TestBundle:Post p  ORDER BY p.date DESC'
        )
    ->setMaxResults(5); 

How to use this result to select from it in the next query?

 return $this->getEntityManager()
    ->createQuery(
        "SELECT  u.username , max(p.date),d.points,l.name 
        FROM $first_query
        JOIN p.location l JOIN p.user u JOIN u.deeds d
        WHERE l.name = :location
        GROUP BY u.id
        ORDER BY d.points DESC , p.date DESC
        "

        )
    ->setParameter('location' , $location)
    ->getResult();

Solution

  • I found out that DQL doesn't support limits so I went for native sql.

    $stmt = $this->getEntityManager()->getConnection()->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    

    This way you can do whatever you want with the $query varaible you can set limits and everythign as it's a normal sql statement.