Filtering of associated entity collection in Symfo

2019-08-05 01:17发布

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

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

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

ProducerController:

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

Result:

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

How to do it?

2条回答
Juvenile、少年°
2楼-- · 2019-08-05 01:42

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();

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.

查看更多
\"骚年 ilove
3楼-- · 2019-08-05 01:51

If you want just on result you need to use the findOneBy prefix:

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

You have to use the right name of your attribute here you have translations so it will be findOneByTranslations.

查看更多
登录 后发表回答