2013-05-13 153 views
0

這是我想用Doctrine2來實現查詢:如何在Doctrine2中編寫此查詢? (子查詢+連接)

SELECT d1_.codeLieu AS codeLieu1, d1_.nomLieu AS nomLieu2, d1_.lngLieu AS lngLieu3, d1_.latLieu AS latLieu4, m2_.libelleMention AS libelleMention5, t3_.libelleType AS libelleType6, COUNT(b0_.id) AS sclr0 
FROM Delegation  d1_ 
    INNER JOIN EtablissementBac e5_ ON e5_.delegation_id = d1_.codeLieu 
    INNER JOIN TypeBac   t3_ 
    INNER JOIN MentionBac  m2_ 
    LEFT JOIN Bac    b0_ 
          ON b0_.etabBac_id = e5_.codeLieu -- 1st clause 
          AND b0_.typeBac_id = t3_.codeType -- 2nd clause 
          AND b0_.mentionBac_id = m2_.codeMention -- 3rd clause 
WHERE m2_.codeMention IN ('TB', 'B') 
AND t3_.codeType IN ('114', '129') 
AND d1_.codeLieu IN('01','02','03','38','49','58') 
GROUP BY d1_.codeLieu, m2_.codeMention, m2_.libelleMention, t3_.codeType, t3_.libelleType, t3_.abbrType 
ORDER BY d1_.codeLieu ASC , b0_.mentionBac_id ASC , b0_.typeBac_id ASC 

我遇到一些麻煩的第2和第Bac表的第3條款。關於如何使用Doctrine2來實現它的任何想法?由於請求是動態構建的,因此我不能使用本機SQL,這就是爲什麼我需要使用DQL構建它。

+0

任何人都可以幫助我嗎? – Sherlock 2013-05-13 18:57:47

+0

你想要輸出什麼?一個東西 ?標量結果數組?這不是一個困難的查詢。 – 2013-05-13 23:02:44

+0

數組的數組(如在選擇部分中) – Sherlock 2013-05-13 23:28:58

回答

0

使用「任意JOIN語法」。

$qb 
    ->select(array('d.codeLieu', 'd.nomLieu', 'd.lngLieu', 'd.latLieu', 'm.libelleMention', 't.libelleType', 'COUNT(b.id) AS sclr')) 
    ->from('PFA\SIGBundle\Entity\Delegation', 'd') 
    ->innerJoin('PFA\SIGBundle\Entity\EtablissementBac', 'e', \Doctrine\ORM\Query\Expr\Join::WITH, $qb->expr()->eq('IDENTITY(e.delegation)', 'd.codeLieu')) 
    ->innerJoin('PFA\SIGBundle\Entity\TypeBac', 't') 
    ->innerJoin('PFA\SIGBundle\Entity\MentionBac', 'm') 
    ->leftJoin('PFA\SIGBundle\Entity\Bac', 'b', \Doctrine\ORM\Query\Expr\Join::WITH, $qb->expr()->andX(
     $qb->expr()->eq('IDENTITY(b.etabBac)', 'e.codeLieu'), 
     $qb->expr()->eq('IDENTITY(b.typeBac)', 't.codeType'), 
     $qb->expr()->eq('IDENTITY(b.mentionBac)', 'm.codeMention') 
    )) 
    ->where($qb->expr()->andX(
     $qb->expr()->in('m.codeMention', ':codeMention'), 
     $qb->expr()->in('t.codeType', ':codeType'), 
     $qb->expr()->in('d.codeLieu', ':codeLieu') 
    )) 
    ->groupBy('d.codeLieu') 
    ->addGroupBy('m.codeMention') 
    ->addGroupBy('m.libelleMention') 
    ->addGroupBy('t.codeType') 
    ->addGroupBy('t.libelleType') 
    ->addGroupBy('t.abbrType') 
    ->orderBy('d.codeLieu', 'ASC') 
    ->addOrderBy('m.codeMention', 'ASC') 
    ->addOrderBy('t.codeType', 'ASC') 
    ->setParameters(array(
     'codeMention' => array('TB', 'B'), 
     'codeType' => array('114', '129'), 
     'codeLieu' => array('01', '02', '03', '38', '49', '58') 
    )); 

做一個$qb->getQuery()->getSql()看看這是否匹配你原來的查詢。