Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Doctrine2 entity identifier without knowing its name

I am attempting to create an abstracted getId method on my base Entity class in Symfony2 using Doctrine2 for a database where primary keys are named inconsistently across tables.

When inspecting entity objects I see there is a private '_identifier' property that contains the information I am trying to retrieve but I am not sure how to properly access it.

I'm assuming there is some simple Doctrine magic similar to:

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

But I haven't managed to find it on the intertubes anywhere.

like image 350
Lord_Baine Avatar asked May 25 '11 18:05

Lord_Baine


1 Answers

You can access this information via EntityManager#getClassMetadata(). An example would look like this:

// $em instanceof EntityManager
$meta = $em->getClassMetadata(get_class($entity));
$identifier = $meta->getSingleIdentifierFieldName();

If your entity has a composite primary key, you'll need to use $meta->getIdentifierFieldNames() instead. Of course, using this method, you'll need access to an instance of EntityManager, so this code is usually placed in a custom repository rather than in the entity itself.

Hope that helps.

like image 112
Derek Stobbe Avatar answered Nov 18 '22 05:11

Derek Stobbe