2011-05-09 67 views
8

我想使用查詢生成器實現子查詢,但我不理解語法。我正在處理一個位置表,根據位置類型設置,該表格可以是城市,州或郵政編碼。我想要獲得處於特定狀態的所有地點,並取出任何城市類型並且人口數量低於特定數量的地點。Doctrine 2子查詢

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

在andWhere基本上,我需要說

和其中id不是(從位置選擇id其中LOCATION_TYPE = 1和人口< 1000)

更新:我能夠用直接的DQL來做到這一點,但很高興看到如何使用查詢生成器來完成此操作。

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

看起來我實際上甚至都不需要子查詢。然而,Guilherme還建議我可以使用第二個查詢構建器實例並將其用作in表達式的第二個參數。 http://groups.google.com/group/doctrine-user/browse_thread/thread/f72c104fe334f87c – 2011-05-10 20:09:28

回答

4

教義的文檔,我發現這一點:

// 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 

應該可以把一個子查詢中此功能。我從來沒有用過它,但根據文檔,它應該看起來像這樣。

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

我不是100%確定上面的例子是正確的,但試試看。