2

I have ClassA with a ManyToMany relationship to ClassB, is there a way to Select ClassA entities by ClassB array? Currently I have:

$query = $em->createQuery("
    SELECT a FROM Bundle:ClassA a 
    JOIN a.classB b 
    WHERE b IN (:classBEntities)
    ")
    ->setParameter('classBEntities', $classBEntities);

Being $classBEntities an array of ClassB entities. The problem with that query is that if I'm looking the ClassA entity that have ClassB entities 1, 2 and 3 it returns any ClassA entity that have one of those 3 ClassB entity as well as the one that have the three of them, but I need to select just the ones that have all the entities that the array contains.

4

2 回答 2

2
$queryBuilder = $em
   ->getRepository('Bundle:ClassA')
   ->createQueryBuilder('a')
   ->leftJoin('a.classB', 'b')
;

foreach ($classBentities as $entity) {
    $queryBuilder
        ->andWhere('b IN (:b_entity)')
        ->setParameter('b_entity', array($entity))
    ;
}

$queryBuilder
   ->add('where', $queryBuilder->expr()->count('b'), '=' , ':count_b')
   ->setParameter('count_b', count($classBentities))

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

你需要 Doctrine >= 2.1 才能工作。

于 2013-10-28T09:22:10.693 回答
1

在使用 nifr 答案反复试验后,我得到了解决方案,如果有人遇到同样的问题:

$queryBuilder = $em->getRepository('Bundle:ClassA')
                    ->createQueryBuilder('a')
                    ->join('a.classB', 'b');
                    ->groupBy('a.id')
                    ->having('COUNT(b) = :cB')
                    ->setParameter('cB', count($classBEntities));

           foreach ($classBEntities as $entity) 
           {
               $id = $entity->getId();
               $queryBuilder
                ->join('a.classB', 'b'.$id)
                ->andWhere('b'.$id.'.id IN (:b_entity'.$id.')')
                ->setParameter('b_entity'.$id, array($id));
           }

$result = $queryBuilder->getQuery()->getResult();
于 2013-11-03T21:01:53.400 回答