Fetch highest ID from database via Doctrine

doctrine-orm, symfony

Solution

Use `MAX` function and fetch a single scalar result:

$highest_id = $em->createQueryBuilder()
    ->select('MAX(e.id)')
    ->from('YourBundle:Entity', 'e')
    ->getQuery()
    ->getSingleScalarResult();

To fetch the last object you may just do the following:

$last_entity = $em->createQueryBuilder()
    ->select('e')
    ->from('YourBundle:Entity', 'e')
    ->orderBy('e.id', 'DESC')
    ->setMaxResults(1)
    ->getQuery()
    ->getOneOrNullResult();

Problem

After trying a lot of howto's on Google I am still without answers. I want to fetch an object from the database which has the highest ID (ai). I know this must be very simple to do, but I couldn't find the solution. In the database I have the entities Syncs which have an auto-increment ID. I need that (latest) object to retrieve the value `<end>` which is a DateTime. (It is in Symfony via Doctrine by the way.)

Original source