在Symfony / Doctrine中过滤关联的实体集合

时间:2016-01-07 21:45:04

标签: symfony doctrine-orm

如果我有一个作为集合的关联对象,我可以限制结果吗?

例如:生产者实体具有属性翻译,其中包含其他实体的集合(ProducerTranslation)。

class Producer
{
    protected $id;
    // ArrayCollection
    protected $translations;
}

ProducerController:

$producers = $this->getDoctrine()
    ->getRepository('ProducerBundle:Producer')
    ->findAll();

结果:

Producer
    id: 1
    translations:
        en: ProducerTranslation
        de: ProducerTranslation

没关系。但我想只获得一种语言的一个实体。 预期结果:

$producers = $this->getDoctrine()
    ->getRepository('ProducerBundle:Producer')
    ->findByLocale('en');

Producer
    id: 1
    translations:
        en: ProducerTranslation

怎么做?

2 个答案:

答案 0 :(得分:1)

要限制子集合,您可以使用这样的querybuilder(假设locale是ProducerTranslation的属性):

$qb = $this->getEntityManager()->createQueryBuilder();

$qb->select('p, pt')
    ->from('ProducerBundle:Producer', 'p')
    ->join('p.translations', 'pt')
    ->where($qb->expr()->eq('pt.locale', ':locale'))
    ->setParameter('locale', 'en')
    ->getQuery()
    ->getResult();

那就能得到你想要的东西。请注意,select('p,pt')部分很重要,因为它只会将您想要的项目提取到集合结果中。

答案 1 :(得分:0)

如果您只想获得结果,则需要使用findOneBy前缀:

$producers = $this->getDoctrine()
        ->getRepository('ProducerBundle:Producer')
        ->findOneByTranslations('en');

您必须在translations处使用属性的正确名称,因此它将为findOneByTranslations