Subquery in doctrine2 notIN Function

亡梦爱人 提交于 2019-11-27 07:50:45
WizardZ

The same alias cannot be defined 2 times in the same query

$qb  = $this->_em->createQueryBuilder();
$qb2 = $qb;
$qb2->select('m.id')
    ->from('Custom\Entity\MembreService', 'ms')
    ->leftJoin('ms.membre', 'm')
    ->where('ms.id != ?1');

$qb  = $this->_em->createQueryBuilder();
$qb->select('mm')
    ->from('Custom\Entity\Membre', 'mm')
    ->where($qb->expr()->notIn('mm.id', $qb2->getDQL())
);
$qb->setParameter(1, $service);
$query  = $qb->getQuery();

return $query->getResult();

Ideally you should use many-to-many relation for your entity, in this case your query is going to be much simpler.

Actually if you are using the Symfony2 repository class you could also do the following:

$in = $this->getEntityManager()->getRepository('Custom:MembreService')
    ->createQueryBuilder('ms')
    ->select('identity(ms.m)')
    ->where(ms.id != ?1);

$q = $this->createQueryBuilder('m')
    ->where($q->expr()->notIn('m.id', $in->getDQL()))
    ->setParameter(1, $service);

return $q->getQuery()->execute();
Stephan Vierkant

You can use (NOT) MEMBER OF:

<?php
$query = $em->createQuery('SELECT m.id FROM Custom\Entity\Membre WHERE :service NOT MEMBER OF m.services');
$query->setParameter('service', $service);
$ids = $query->getResult();

See the documentation for more examples.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!