1

In my Symfony2/doctrine2 application, I have two entities, Media and Recipe.

They can be linked by a oneToMany or a ManyToMany association.

In the case of a oneToMany relationship, I am using the following code to retrieve the Recipe linked to an instance of Media :

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

However, if the relationship is a manyToMany, and also if I gave a custom name to the property, the previous code does not work.

How can I programatically retrieve the "recipes" of the mappedBy from the annotation mapping of the Media class ?

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

2 Answers 2

4

What you need is a class that implements Doctrine\Common\Annotations\Reader interface. It is registered as a annotation_reader service. Having this class you can get annotations of various objects using methods like getClassAnnotation, getMethodAnnotations etc. In your case a getPropertyAnnotations seems to be a good choice:

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

$annotations is a collection of annotations. In your case there will be 3 elements. Check doc for more info

Sign up to request clarification or add additional context in comments.

Comments

2

You can receive information about mapping from entities' metadata.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.