简体   繁体   English

Doctrine 2 DQL-通过精确的ManyToMany数组选择

[英]Doctrine 2 DQL - Select by exact ManyToMany array

I have ClassA with a ManyToMany relationship to ClassB, is there a way to Select ClassA entities by ClassB array? 我有与ClassB有ManyToMany关系的ClassA,是否可以通过ClassB数组选择ClassA实体? 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. 作为$ classBEntities,是ClassB实体的数组。 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. 该查询的问题在于,如果我正在查找具有ClassB实体1、2和3的ClassA实体,它将返回具有这3个ClassB实体之一和具有这三个ClassB实体的任何ClassA实体,但是我只需要选择具有数组包含的所有实体的实体即可。

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

You will need Doctrine >= 2.1 for this to work. 您需要Doctrine> = 2.1才能起作用。

After some trial and error using nifr answer I got the solution, here it is if someone ran into the same problem: 经过使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM