How to get Doctrine2 entity identifier without knowing its name

余生颓废 提交于 2020-02-15 07:10:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6128914/how-to-get-doctrine2-entity-identifier-without-knowing-its-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!