views:

192

answers:

3

How can I get the last insert id with doctrine 2 ORM? I didn't find this in the documentation of doctrine, is this even possible?

+1  A: 

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

$em->persist($user);
$em->flush();
$user->getId();
Skelton
+1  A: 

Calling flush() can potentially add lots of new entities, so there isnt really the notion of "lastInsertId". However Doctrine will populate the identity fields whenever one is generated, so accessing the id field after calling flush will always contain the ID of a newly "persisted" entity.

beberlei
A: 

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

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

You do not need to flush in order to get this id. Flushing actually saves the in-memory object map to the database, so use sparingly.

Sleepy