2016-01-07 44 views
1

如果我有一個關聯對象是一個集合,我可以限制結果嗎?在Symfony/Doctrine中過濾關聯實體集合

例如:生產者實體具有屬性翻譯,其中包含其他實體(生產者翻譯)的集合。

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 

如何做到這一點?

回答

1

要限制一個子集,你可以使用QueryBuilder的這樣的(假設區域是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')部分很重要,因爲它只會將所需的項目提取到收集結果中。

0

如果你想只是結果,您需要使用findOneBy前綴:

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

你必須使用你的屬性的名稱權在這裏你有translations所以這將是findOneByTranslations