Get the last insert id with doctrine 2?

2019-01-21 18:34发布

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?

5条回答
叼着烟拽天下
2楼-- · 2019-01-21 18:52

A bit late to answer the question. But,

If it's a MySQL database

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

查看更多
再贱就再见
3楼-- · 2019-01-21 18:55

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.

查看更多
倾城 Initia
4楼-- · 2019-01-21 18:57

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-21 19:02

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

$em->persist($user);
$em->flush();
$user->getId();
查看更多
叼着烟拽天下
6楼-- · 2019-01-21 19:02

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 do need to flush in order to get this id.

Syntax Error Fix: Added semi-colon after $entityManager->flush() is called.

查看更多
登录 后发表回答