3

在 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);
4

1 回答 1

4
// $em being your EntityManager..

if ($em->getClassMetadata($className)->getAssociationMapping($fieldName))
{
   ....
}
于 2012-05-15T09:19:03.737 回答