Doctrine2 Insert and retrieve new insert ID

PhpDoctrine Orm

Php Problem Overview


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);

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

One can use the Doctrine\DBAL\Connection::lastInsertId() method.

It can be used with native queries as well as manually written inserts.

Example case:

$query = 'INSERT INTO blabla...';
$connection->executeUpdate($query, $params);

var_dump($connection->lastInsertId());

If using the ORM, you can obtain an instance of the connection from the entity manager:

$connection = $em->getConnection();

Note:
Aside from the technical details, I agree with @Layke for using an entity for your specific case.

Solution 3 - Php

Providing that your Entity which are you are trying to set has

   /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    private $id;

Then when you persist your object, the entity manager will populate the Entity which you are trying to persist with the ID.

Some caveats however, is that you can't do this with composite keys post obviously, and you obviously have to flush all Entities. So if you detach an Entity which has an association to the persisted entity that you are trying to get the ID for, then you won't be able to retrieve the ID.

Aside from that Flask's answer is bang on.

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

Solution 4 - Php

$conn->lastInsertId();will get you the last inserted ID when only using Doctrine's DBAL (sans ORM).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNimmoNetView Question on Stackoverflow
Solution 1 - PhpFlaskView Answer on Stackoverflow
Solution 2 - PhpNikola PetkanskiView Answer on Stackoverflow
Solution 3 - PhpLaykeView Answer on Stackoverflow
Solution 4 - PhpBramusView Answer on Stackoverflow