Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch highest ID from database via Doctrine

Tags:

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

like image 228
John Doe Avatar asked Jun 04 '14 13:06

John Doe


People also ask

How do I get maximum ID records in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

What is Max ID in MySQL?

MySQL supports two-byte collation IDs. The range of IDs from 1024 to 2047 is reserved for user-defined collations.


1 Answers

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(); 
like image 96
VisioN Avatar answered Sep 19 '22 19:09

VisioN