Symfony Doctrine数据类型只适用于findBy而不是querybuilder
问题描述:
我有自定义数据类型,它在按照预期使用FindBy时工作...但在使用查询生成器时不起作用。对不起,很长的文章,但我想更多的信息应该有所帮助。Symfony Doctrine数据类型只适用于findBy而不是querybuilder
它是相同的,因为这没有答案的问题: Doctrine 2 Custom Types
数据类型:
...
class MyHappyType extends Type
{
...
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return 'hippies: '.$value;
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return 'doubleHippies: '.$value;
}
...
public function getName()
{
return 'hippies';
}
}
实体:
// Entity class
...
class Hippie
{
/**
* @ORM\Id
* @ORM\Column(type="integer", unique=true)
*/
protected $id;
/*
* @ORM\Column(type="hippies")
*/
protected $Sandals;
}
库:
...
class HippiesRepository extends EntityRepository
{
public function useQueryBuilder($sandals){
$qb = $this->createQueryBuilder('hippie');
$qb->select('hippie')
->where('hippie.Sandals = :sandals')
->setParameter('sandals', $sandals);
return $qb->getQuery()->getResult();
}
}
最后,控制器:
public function hippiesAction()
{
// this returns an entity with $hippie1->sandals == 'doubleHippies: hippies: red'
// which is expected behaviour
$hippie1 = $em->getRepository('HappyHippiesBundle:Hippie')->findOneBySandals('red');
// this one returns no results, when checking queries run I see that
// $sandals value isn't translated in to 'hippies: red'
$hippie2 = $em->getRepository('HappyHippiesBundle:Hippie')->useQueryBuilder('red');
}
因此,在短期,使用QueryBuilder的数据类型时不被转换,只用FindBy时...
答
您需要在实体配置定义库类:
/**
* @ORM\Entity(repositoryClass=""AcmeDemoBundle\Entity\HippiesRepository")
*/
class Hippie
{
// ...
}
查看Custom Repository classes了解更多信息。
更新:
你也可以摆脱->select('hippie')
的。当您使用该方法在存储库类中创建QueryBuilder
时,该方法将自动为您调用select
和from
方法(有关更多信息,请参阅EntityRepository.php文件)。在这种情况下,您所需要做的只是:
$qb = $this->createQueryBuilder('hippie');
$qb->where('hippie.Sandals = :sandals')
->setParameter('sandals', $sandals);
return $qb->getQuery()->getResult();
再考虑一下,使用查询构建器时不会考虑自定义类型。它们连接到实体,它与查询无关 - 这只是一个查询。 所以我想问题是:你如何在自定义类型的仓库中使用方法? – offwhite 2014-09-18 08:34:20