【问题标题】:Symfony2 / Doctrine2 : how to access an entity annotation mapping?Symfony2 / Doctrine2:如何访问实体注释映射?
【发布时间】:2015-05-25 17:40:30
【问题描述】:

在我的 Symfony2/doctrine2 应用程序中,我有两个实体,Media 和 Recipe。

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

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

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

但是,如果关系是多对多,并且如果我为属性指定了自定义名称,则前面的代码不起作用。

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

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

【问题讨论】:

    标签: symfony doctrine-orm annotations mapping accessor


    【解决方案1】:

    你需要的是一个实现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 是注解的集合。在您的情况下,将有 3 个元素。查看doc了解更多信息

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        • 1970-01-01
        • 2015-08-16
        • 1970-01-01
        相关资源
        最近更新 更多