检查是否存在关联而不在Doctrine2中捕获异常?

时间:2012-05-14 20:25:06

标签: php symfony doctrine doctrine-orm

在Doctrine2中发出查询之前,是否可以检查关联是否存在?例如:

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

我想检查(实际上没有发出查询本身)它存在关联product.features

编辑:出于好奇,我正在编写服务(真的是帮助者),根据GET参数进行一些收集过滤:

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
}

相关部分将是:

$this->getEntitiesUtility()->checkRelation($entityName, $relationName);

1 个答案:

答案 0 :(得分:4)

// $em being your EntityManager..

if ($em->getClassMetadata($className)->getAssociationMapping($fieldName))
{
   ....
}