Get the last insert id with doctrine 2?
Solution 1:
I had to use this after the flush to get the last insert id:
$em->persist($user);
$em->flush();
$user->getId();
Solution 2:
You can access the id after calling the persist and flush methods of the entity manager.
$widgetEntity = new WidgetEntity();
$entityManager->persist($widgetEntity);
$entityManager->flush();
$widgetEntity->getId();
You must call flush in order to get this id.
Solution 3:
If you're not using entities but Native SQL as shown here then you might want to get the last inserted id as shown below:
$entityManager->getConnection()->lastInsertId()
For databases with sequences such as PostgreSQL please note that you can provide the sequence name as the first parameter of the lastInsertId
method.
$entityManager->getConnection()->lastInsertId($seqName = 'my_sequence')
For more information take a look at the code on GitHub here and here.