Take the 2-minute tour ×

Would be possible to check if an association exists before issuing a query in Doctrine2? Example:

 * @ORM\Entity
class Product
     * @ORM\OneToMany(targetEntity="Feature", inversedBy="product")
    public $features;

I'd like to check (actually without issuing the query itself) it the association product.features exists.

EDIT: Out of curiosity i'm writing a service (an helper, really) to do some collection filtering based on GET paramters:

public function initialize($entityName, $key)
    // Defaults are empty values and empty collection
    $this->values     = array();
    $this->collection = new ArrayCollection();

    // If "$key" GET parameter is null or blank return this instance
    if(is_null($value = $this->request->get($key))
        || strlen(trim($value)) == 0) return $this;

    // Split the parameter value based on separator (typically a comma)
    $re = '/\s*' . $this->separator . '\s*/';

    // Return this instance if no values are found
    if(!($set = preg_split($re, $value, 0, PREG_SPLIT_NO_EMPTY))) return $this;

    // Guess the repository fully qualified name and entity name
    $guesser    = $this->getManagementGuesser();
    $repoName   = $guesser->guessRepositoryName();
    $entityName = $guesser->guessEntityName();

    // Get the repository for the entity and create the builder
    $qb = $this->getRepository($repoName)->createQueryBuilder('e');

    // Check if a relation named $key exists and throw a LogicException
    $exists = $this->getEntitiesUtility()->checkRelation($entityName, $key);
    if(!$exists) throw new \LogicException("Relation named '$key' not found.");

    // Other stuff

The relavant part would be:

$this->getEntitiesUtility()->checkRelation($entityName, $relationName);
share|improve this question
You mean if a given product has at least one associated feature record? You have to perform a query to do that. –  Peter Bailey May 14 '12 at 21:04
@PeterBailey nope, i know i can inner join it. I'm talking about if product has actually a relation named "features". –  Polmonino May 14 '12 at 22:28
Get the class metadata and loop through it to check if such relation has been defined in the entity. However I would go further to know why are you asking this because I suspect you're trying to solve so polymorphism problems or something like that, and there are better way to do if you are. –  Boris Guéry May 14 '12 at 23:06
@BorisGuéry thank you for be interested in this. You are talking about simply checking (statically, it you understand what i mean) that $features actually exists? $features can exists of course without being a relation itself (could be merely a property). See my edits for the other question, and thanks for helping. –  Polmonino May 15 '12 at 0:29

1 Answer 1

up vote 2 down vote accepted
// $em being your EntityManager..

if ($em->getClassMetadata($className)->getAssociationMapping($fieldName))
share|improve this answer

Your Answer


