Get the last insert id with doctrine 2?
Asked Answered
A

8

88

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?

Attwood answered 18/8, 2010 at 6:1 Comment(1)
try this, at the end of your insert return the id... like return $this->id;Monotheism
A
186

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

$em->persist($user);
$em->flush();
$user->getId();
Attwood answered 18/8, 2010 at 8:34 Comment(5)
Cant use it. Getting error Call to undefined method Test\Entity\Test::getId() in "My Project"Stylographic
@Stylographic You need to define a public getter for your Id (if this one is private as it should be)Munn
@cheesemacfly: I already sorted this out this error is generated (in my scenario) when we are unable To flush() for any reason, once Flush() is executed successfully getID() starts working, assuming getter and setters are not a issue hereStylographic
What if I persist() the entity in a loop and flush() after that? I'm trying to figure that out, but no luck so far.Piny
assign id to variable : code $id = $user->getId(); codeEffulgence
S
46

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.

Stulin answered 20/8, 2010 at 10:3 Comment(0)
K
35

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.

Kurtis answered 10/11, 2014 at 16:24 Comment(4)
This might not work with every DBMS. For instance it does not work with Postgres (because of sequences)Fachini
Awesome!! I spent hours looking for this little snippet.Nunci
@Fachini You just need to know the name of the sequence, eg: lastInsertId('articles_id_seq')Thoracoplasty
You can also get the name of the sequence like this: $conn = $this->getDoctrine()->getConnection(); $metadata = $em->getClassMetadata('\App\Entity\YourClass'); $seqName = $metadata->getSequenceName($conn->getDatabasePlatform()); Works :-)Support
P
10

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.

Platitudinous answered 19/8, 2010 at 12:23 Comment(0)
L
2

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.

Limnetic answered 15/12, 2010 at 12:53 Comment(0)
P
2

In my case, as I declared $id as private I just created a new public method to get it.

public function getId() {
 return $this->id;
}

So then I could call it like so

    $user = new User();
    $user->setUsername("Kylo Ren");
    $entityManager = getEntityManager();
    $entityManager->persist($user);
    $entityManager->flush();
    echo "Created User with ID " . $user->getId() . "\n";
Predictory answered 22/8, 2021 at 14:50 Comment(0)
S
1

Here i post my code, after i have pushed myself for one working day to find this solution.

Function to get the last saved record :

private function getLastId($query) {
        $conn = $this->getDoctrine()->getConnection();
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $lastId = $stmt->fetch()['id'];
        return $lastId;
    }

Another Function which call the above function

private function clientNum() {
        $lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
        $noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
        return $noClient;
    }
Scoot answered 15/11, 2019 at 15:24 Comment(0)
K
0

More simple: SELECT max(id) FROM client

Kwangchow answered 5/5, 2020 at 15:5 Comment(1)
Not a good idea for concurrent and big systems.Pedant

© 2022 - 2024 — McMap. All rights reserved.