如何在不知道其名称的情况下获取Doctrine2实体标识符 [英] How to get Doctrine2 entity identifier without knowing its name

查看:117
本文介绍了如何在不知道其名称的情况下获取Doctrine2实体标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Doctrine2在我的Symfony2的基础Entity类上为数据库创建抽象的getId方法,该数据库的主键在表之间的名称不一致。

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.

检查时我看到的实体对象有一个私有的'_identifier'属性,其中包含我要检索的信息,但不确定如何正确访问它。

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();
}

但是我没有设法在任何地方的Intertube上找到它。

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

推荐答案

您可以通过 EntityManager#getClassMetadata()访问此信息。一个示例如下所示:

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();

如果您的实体具有复合主键,则需要使用而是使用$ meta-> getIdentifierFieldNames()。当然,使用此方法,您将需要访问 EntityManager 的实例,因此此代码通常放置在自定义存储库,而不是实体本身。

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.

希望有帮助。

这篇关于如何在不知道其名称的情况下获取Doctrine2实体标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆