NimmoNet NimmoNet - 3 months ago 24
PHP Question

Doctrine2 Insert and retrieve new insert ID

In Doctrine2 using some thing like:

$user = array('username' => 'example', 'passsword' => 'changeme');

$conn->insert('users', $user);


How would I then get the last ID of the user I just inserted? If it is not possible to do this then how do you gen a id so that you can the following:

$id = //something here.
$user = array('username' => 'example', 'passsword' => 'changeme', 'id' => $id);
$conn->insert('users', $user);

Answer

If you are using the ORM

$em->persist($object);
$em->flush();
$object->getId();

if you are using the DBAL:

$conn->lastInsertId();

http://www.doctrine-project.org/api/dbal/2.5/class-Doctrine.DBAL.Connection.html#_lastInsertId