How to get Doctrine2 entity identifier without knowing its name

后端 未结 1 1463
Happy的楠姐
Happy的楠姐 2021-01-17 16:29

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

相关标签:
1条回答
  • 2021-01-17 16:51

    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.

    0 讨论(0)
提交回复
热议问题