繁体   English   中英

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

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

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

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

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

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

但是,如果关系是manyToMany,并且如果我给属性指定了自定义名称,则先前的代码将无法工作。

如何从Media类的注释映射中以编程方式检索mapledBy的“食谱”?

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

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

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

$annotations$annotations的集合。 在您的情况下,将包含3个元素。 检查文档以获取更多信息

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM