Symfony2 / Doctrine2:如何访问实体注释映射?

Symfony2 / Doctrine2 : how to access an entity annotation mapping?

在我的 Symfony2/doctrine2 应用程序中,我有两个实体,媒体和食谱。

它们可以通过 oneToMany 或 ManyToMany 关联进行链接。

在 oneToMany 关系的情况下,我使用以下代码来检索链接到 Media 实例的食谱:

$accessor = PropertyAccess::createPropertyAccessor();
$reflect = new ReflectionClass($media);
$shortName =  $reflect->getShortName();
$value = $accessor->getValue($element, $shortName);

但是,如果关系是多对多关系,而且如果我给 属性 一个自定义名称,前面的代码就不起作用。

如何以编程方式从媒体 class 的注释映射中检索 mappedBy 的 "recipes"?

/**
 * @ORM\OrderBy({"sortablePosition" = "ASC"})
 * @Assert\Valid()
 * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\Core\Media", mappedBy="recipes", cascade={"persist", "remove"})
 */
protected $medias;

您需要的是实现 Doctrine\Common\Annotations\Reader 接口的 class。它被注册为 annotation_reader 服务。有了这个 class,您可以使用 getClassAnnotationgetMethodAnnotations 等方法获得各种对象的注释。在您的情况下,getPropertyAnnotations 似乎是一个不错的选择:

$reflClass = new \ReflectionClass($class); //$class is an instance of your entity
$refProp = $reflClass->getProperty('medias');
$annotations = $reader->getPropertyAnnotations($refProp);

$annotations是注释的集合。在您的情况下,将有 3 个元素。检查 doc 了解更多信息

您可以从实体的元数据中接收有关映射的信息。

$metadata = $this->getDoctrine()
   ->getManager()
   ->getMetadataFactory()
   ->getMetadataFor(\Doctrine\Common\Util\ClassUtils::getClass($object))
;