教义2子查询

Jer*_*cks 8 subquery doctrine-orm

我想使用查询构建器实现子查询,但我不理解语法.我正在处理一个位置表,该表具有可以是城市,州或邮政编码的条目,具体取决于所设置的位置类型.我希望获得所有处于某种状态的地点并取出任何城市类型并且人口数量低于一定数量的地点.

$qb->select('l')
->from('Entity\Location', 'l')
->where('l.state = :state')
->setParameter('state', 'UT')
->andWhere('...don't know what to put here');
Run Code Online (Sandbox Code Playgroud)

在和我在哪里我基本上需要说

并且id不在(从location_type = 1和population <1000的位置选择id)

更新:我能够使用直接DQL执行此操作,但很高兴看到如何使用查询生成器执行此操作.

$qb->andWhere('l.id NOT IN (SELECT l2.id FROM Entity\Location AS l2 WHERE l2.location_type = 1 AND l2.population < 1000)');
Run Code Online (Sandbox Code Playgroud)

Ren*_*gen 4

在 Doctrine 的文档中我发现了这一点:

// Example - $qb->expr()->in('u.id', array(1, 2, 3))
// Make sure that you do NOT use something similar to $qb->expr()->in('value', array('stringvalue')) as this will cause Doctrine to throw an Exception.
// Instead, use $qb->expr()->in('value', array('?1')) and bind your parameter to ?1 (see section above)
public function in($x, $y); // Returns Expr\Func instance

// Example - $qb->expr()->notIn('u.id', '2')
public function notIn($x, $y); // Returns Expr\Func instance
Run Code Online (Sandbox Code Playgroud)

应该可以在这个函数中放置一个子查询。我自己从未使用过它,但根据文档它应该看起来像这样。

$qb->select('l')
   ->from('Entity\Location', 'l')
   ->where('l.state = :state')
   ->setParameter('state', 'UT')
   ->andWhere($qb->expr()->notIn('u.id', 
       $qb->select('l2.id')
          ->from('Entity\Location', 'l2')
          ->where(l2.location_type = ?1 AND l2.population < ?2)
          ->setParameters(array(1=> 1, 2 => 1000))
));
Run Code Online (Sandbox Code Playgroud)

我不能 100% 确定上面的示例是否正确,但请尝试一下。