Get last insert ID with doctrine 2?

How can I get the last insert ID with doctrine 2 ORM? I did not find this in the documentation of the doctrine, is this possible?

+57
php orm doctrine lastinsertid
Aug 18 '10 at 6:01
source share
5 answers

I had to use this after the flush to get the last insert id:

$em->persist($user); $em->flush(); $user->getId(); 
+134
Aug 18 2018-10-18T00:
source share

You can access the id after calling the persist method of the entity manager.

 $widgetEntity = new WidgetEntity(); $entityManager->persist($widgetEntity); $entityManager->flush(); $widgetEntity->getId(); 

You need to collapse to get this identifier.

Syntax error fixed: added semicolon after calling $ entityManager-> flush ().

+29
Aug 20 '10 at 10:03
source share

If you are not using entities, but Native SQL, as shown here , you may need to get the last inserted identifier, as shown below:

 $entityManager->getConnection()->lastInsertId() 

For databases with sequences such as PostgreSQL , please do not specify that you can specify the sequence name as the first parameter of the lastInsertId method.

 $entityManager->getConnection()->lastInsertId($seqName = 'my_sequence') 

For more information, check out the GitHub code here and.

+17
Nov 10 '14 at 16:24
source share

Calling flush () can potentially add many new objects, so there really is no such thing as "lastInsertId". However, Doctrine will populate the identifier fields whenever it is generated, so accessing the id field after calling flush will always contain the identifier of the newly "saved" object.

+9
Aug 19 '10 at 12:23
source share

A bit late to answer the question. But,

If it is a MySQL database

should $doctrine_record_object->id work if AUTO_INCREMENT is defined in the database and in your table definition.

+3
Dec 15 '10 at 12:53
source share



All Articles