Symfony2 Doctrine:设置参数以获取带有clausule实例的查询

时间:2012-01-05 18:52:47

标签: symfony doctrine-orm

我有单表继承的跟随类:

/**
* @ORM\Entity
* @ORM\Entity(repositoryClass="MyProject\MyBundle\Repository\ParameterRepository")
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap({"MidUpperArmCircumference" = "MyProject\MyBundle\Entity\MidUpperArmCircumference", "parameter" = "Parameter"})
*/
class Parameter{
...
}

我试图获取MidUpperCircumference的实例:

...
$repository = $this->getDoctrine()->getRepository('MyprojectMyBundle:Parameter');
$discr = 'MyProject\MyBundle\Entity\MidUpperArmCircumference';
$midUpper = $repository->findOneByDiscr($discr);

我也有这个:

//MyProject\MyBundle\Repository\ParameterRepository

...
public function findOneByDiscr($discr)
{

    $query = $this->getEntityManager()
    ->createQuery(
            'SELECT u FROM MyProjectMyBundle:Parameter u 
            WHERE u INSTANCE OF :entity ')
            ->setParameter('entity', $discr);


    try {
        return $query->getSingleResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }

}

我收到了这个错误:

  

警告:get_class()期望参数1为对象,字符串在D:\ workspace \ Project \ Symfony2 \ vendor \ doctrine \ lib \ Doctrine \ ORM \ Query \ SqlWalker.php第1727行中给出

2 个答案:

答案 0 :(得分:0)

要获取 MidUpperCircumference 对象的实例,您需要:

<?php
use MyProject\MyBundle\Entity\MidUpperArmCircumference

...
$repository = $this->getDoctrine()->getRepository('MyprojectMyBundle:Parameter');
$discr = new MidUpperCircumference();
$midUpper = $repository->findOneByDiscr($discr);
...

答案 1 :(得分:0)

您也可以尝试设置参数(实体)的数据类型,如下所示:

    ->setParameter('entity', $discr, \Doctrine\DBAL\Types\Type::OBJECT);