0

I have a User entity that have sectors associated (such as sector A,B,C and so on)

(Sector is an entity too)

Then I have a Document entity that have sectors associated too

I want to retrieve all Documents where its sectors are in the User entity...

How to do that with doctrine?

$repo    = $this->getDoctrine()->getRepository('MyBundle:Document');
$sectors = $this->getUser()->getSectors();

$repo->findBy(['sectors'=>???]);
Francesco
  • 555
  • 4
  • 23

1 Answers1

0

This one should be enough:

$repo = $this->getDoctrine()->getRepository('MyBundle:Document');
$sectors = $this->getUser()->getSectors();
$sectorIds = array_map(function($sector) { return $sector->getId(); }, $sectors);

$queryBuilder = $repo->createQueryBuilder('document');
$queryBuilder
    ->lefJoin('document.sectors', 'sector')
    ->where('sector.id IN (:sectorIds)')
    ->setParameter('sectorIds', $sectorIds);

$documents = $queryBuilder->getQuery()->getResult();

Inspired from How to use WHERE IN with Doctrine 2

Community
  • 1
  • 1
chalasr
  • 12,971
  • 4
  • 40
  • 82
  • No, it will not work because Docs can have more than one sector. For example User has sectors A,B and Doc1 has sectors A,B,C, and Doc2 has sector A. So I need to retrieve ONLY (in this case) Doc2 (cause Doc1 as sector C too that User doesn't have) – Francesco Jun 15 '16 at 21:22