在Symfony / Doctrine中过滤关联的实体集合 [英] Filtering of associated entity collection in Symfony / Doctrine

查看:117
本文介绍了在Symfony / Doctrine中过滤关联的实体集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个关联对象是一个集合,我可以限制结果?

If I have an associated object that is a collection, I can restrict the results?

例如:生产者实体具有属性转换,其中包含其他实体(ProducerTranslation)。

For example: Producer entity has the property translations, which contains a collection of other entities (ProducerTranslation).

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

ProducerController:

ProducerController:

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

结果:

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

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

It's alright. But I want to get only one entity of a language. Expected result:

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

Producer
    id: 1
    translations:
        en: ProducerTranslation

如何做?

推荐答案

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

To restrict a sub collection you can use querybuilder like this (assuming locale is a property of 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')部分很重要,因为它只会将您想要的项目提取到收集结果中。

That'll get you what you want. Note the select('p, pt') part is important as it will only fetch the items you want into the collection result.

这篇关于在Symfony / Doctrine中过滤关联的实体集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆