2017-08-01 47 views
0

如何將此查詢轉換爲symfony 2準則查詢生成器?學說查詢生成器 - 嵌套查詢

SELECT artist_id,日期,餘額,類型FROM交易爲T1 WHERE 日期=(SELECT MAX(日期)FROM交易WHERE artist_id = t1.artist_id與在 狀態( '部分', '未決', '扣除', '接受'),然後鍵入NOT LIKE '支付')GROUP BY artist_id ORDER BY artist_id

我試過如下:

$qb = $this->getEntityManager()->createQueryBuilder() 
->select('t.balance','a.id','t.date') 
      ->from('TestMainBundle:Transaction','t') 
      ->Join('t.artist','a') 
      ->where("t.status in ('partial','pending','deducted','accepted')") 
      ->andWhere("t.type NOT LIKE 'payment'") 
      ->groupBy('a.id') 
      ->orderBy('a.id'); 
     return $qb->getQuery()->getResult(); 

但我堅持包含max(date)的條件。對此非常感謝。

+0

我想你需要類似這個[問題](https://stackoverflow.com/questions/11924164/subquery-in-doctrine2-notin-function) – squareCircle

回答

1

你的學說查詢將是這個樣子,

$qb1 = $this->getDoctrine()->getManager()->createQueryBuilder();   
$select = $qb1->select('MAX(date) AS max_data') 
     ->from('YourBundle:Transaction', 's') 
     ->where('s.artist_id = :ti_artist_id') 
     ->andWhere('s.status IN (:statuses)') 
     ->andWhere('s.type NOT LIKE :type') 
     ->getQuery(); 

$qb2 = $this->getDoctrine()->getManager()->createQueryBuilder(); 
$result = $qb2->select('t.artist_id', 't.date', 't.balance', 't.type') 
     ->from('YourBundle:Transaction', 't'); 

$result->where($qb2->expr()->eq('t.date', $select->getDQL())) 
     ->setParameter('ti_artist_id', 't.id') 
     ->setParameter('statuses', array('partial','pending','deducted','accepted')) 
     ->setParameter('type', 'payment') //possibly '%payment%' 
     ->orderBy('t.artist_id') 
     ->getQuery() 
     ->getResult(); 

乾杯!

+0

謝謝。它有幫助。 – Programmer

+0

@程序員,非常歡迎您。如果可能,考慮給我一個投票/接受的答案。非常感謝。 –