Reputation: 693
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?
Upvotes: 1
Views: 789
Reputation: 4119
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.
Upvotes: 1
Reputation: 2375
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
.
Upvotes: 0