2012-12-19 24 views
23

我試着重現此查詢:「其中沒有」教義查詢生成器查詢

SELECT * FROM `request_lines` 
where request_id not in(
select requestLine_id from `asset_request_lines` where asset_id = 1 
) 

教義查詢生成器, 我被困在那裏REQUEST_ID不在(選擇

我目前有:

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

回答

33

您需要使用查詢生成器表達式,這意味着你需要訪問查詢生成器對象此外,代碼更容易,如果你生成subsele寫。提前CT名單:

$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(); 
+0

在一個查詢中這是不可能的? – Wilt

+1

是的,檢查我的答案下面... – Wilt

+0

是的,使用Wilt的方法 – Lighthart

21

這是可能做到這一點的一個學說查詢:

$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

+2

坦率地說,我更喜歡這個答案我自己 – Lighthart

+1

@Lighthart哈哈:)你可以upvote,如果你喜歡它... – Wilt

+0

偉大的解決方案,謝謝!可以在邏輯上期望' - > where($ qb-> expr() - > eq('x1.some_id',$ sub> getDql()))'工作的地方使用同樣的方法,但是' > eq(...)'或' - > neq(...)'需要一個文字。只需在(...)或' - > notIn(...)'中使用' - >並將子查詢的結果限制爲單個返回值。 – iisisrael