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 ta
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.