Symfony2: get the id of the persisted object

Miloš picture Miloš · Oct 18, 2012 · Viewed 32.8k times · Source

I have two entity: User and Person.

In the entity User I need the id of the associated person: user_id.

When I am creating a new user, I have to create first the person and then the user. In the user, I have to put the id of the corresponding person and for that I need to get the id of the persisted object person which is an auto increment.

Is it possible to get the id of the object after:

$em->persist($person);
$em->flush();

And how can I do this?

The alternative is to search the biggest id it the table Person and take this one but I think there should be a better and easier method to get the id of the persisted object.

In php for example, when I execute

$articleID = $_DB->queryRaw((....);

I am getting the id like that.

Answer

Habibillah picture Habibillah · Oct 18, 2012

Symfony2 with Doctrine as default ORM will automatically generate an ID after data stored in database. So you can call the ID by ->getId()

$id = $person->getId();