'不在'查询与doctrine查询生成器

时间:2012-12-19 16:58:30

标签: symfony doctrine doctrine-orm doctrine-query

我正在尝试重现此查询:

SELECT * FROM `request_lines`
where request_id not in(
select requestLine_id from `asset_request_lines` where asset_id = 1 
)
在doctrine查询构建器中, 我被困在where_id不在的地方(选择

我目前有:

$linked = $em->createQueryBuilder()
        ->select('rl')
        ->from('MineMyBundle:MineRequestLine', 'rl')
        ->where()
        ->getQuery()
        ->getResult();

2 个答案:

答案 0 :(得分:38)

您需要使用查询构建器表达式,这意味着您需要访问查询构建器对象。此外,如果您提前生成子选择列表,则代码更容易编写:

$qb = $em->createQueryBuilder();

$nots = $qb->select('arl')
          ->from('$MineMyBundle:MineAssetRequestLine', 'arl')
          ->where($qb->expr()->eq('arl.asset_id',1))
          ->getQuery()
          ->getResult();

$linked = $qb->select('rl')
             ->from('MineMyBundle:MineRequestLine', 'rl')
             ->where($qb->expr()->notIn('rl.request_id', $nots))
             ->getQuery()
             ->getResult();

答案 1 :(得分:28)

可以在一个Doctrine查询中执行此操作:

$qb  = $this->_em->createQueryBuilder();
$sub = $qb;

$sub = $qb->select('arl')
          ->from('$MineMyBundle:MineAssetRequestLine', 'arl')
          ->where($qb->expr()->eq('arl.asset_id',1));

$linked = $qb->select('rl')
             ->from('MineMyBundle:MineRequestLine', 'rl')
             ->where($qb->expr()->notIn('rl.request_id',  $sub->getDQL()))
             ->getQuery()
             ->getResult();

检查reference in this answer here