Symfony中如何查询关联DocumentAttendu全为recu=true的ExerciceComptable
检索所有关联实体全满足条件的ExerciceComptable
要筛选出所有关联的DocumentAttendu的recu属性均为true的ExerciceComptable,核心思路是排除存在任意一个recu=false关联实体的记录,而非仅匹配存在recu=true的记录。以下是在ExerciceComptableRepository中的两种实现方式:
方法一:分组统计排除法
通过分组统计关联实体中recu=false的数量,筛选数量为0的记录:
// src/Repository/ExerciceComptableRepository.php namespace App\Repository; use App\Entity\ExerciceComptable; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; class ExerciceComptableRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, ExerciceComptable::class); } public function findAllCompleted(): array { return $this->createQueryBuilder('ec') // 关联到DocumentAttendu实体,别名da ->leftJoin('ec.documentAttendus', 'da') // 按ExerciceComptable分组 ->groupBy('ec.id') // 统计recu=false的数量,等于0则所有关联实体的recu都是true ->having('SUM(CASE WHEN da.recu = false THEN 1 ELSE 0 END) = 0') // 可选:如果要求必须至少有一个关联的DocumentAttendu才视为完成,添加此条件 ->andHaving('COUNT(da.id) > 0') ->getQuery() ->getResult(); } }
方法二:NOT EXISTS子查询法
通过子查询判断是否存在recu=false的关联实体,不存在则符合条件:
public function findAllCompleted(): array { return $this->createQueryBuilder('ec') ->where('NOT EXISTS ( SELECT da FROM App\Entity\DocumentAttendu da WHERE da.exerciceComptable = ec AND da.recu = false )') // 可选:要求至少有一个关联实体时添加 ->andWhere('SIZE(ec.documentAttendus) > 0') ->getQuery() ->getResult(); }
注意事项
- 确保代码中关联属性名与你的实体定义一致:
ec.documentAttendus对应ExerciceComptable中指向DocumentAttendu的一对多关联属性,da.exerciceComptable对应DocumentAttendu中指向ExerciceComptable的多对一关联属性。 - 若允许没有任何关联
DocumentAttendu的ExerciceComptable被视为“完成”,可去掉代码中标记为可选的条件。
内容的提问来源于stack exchange,提问作者Pepito
相关产品推荐
相关产品推荐

