在Symfony2查询构建器中转换本机sql查询(使用select in join)

时间:2014-04-02 15:00:08

标签: symfony doctrine-orm

我有这个(巨大的)sql查询转换成doctrine2。

我已成功使用createNativeQuery(),但有时结果与原始结果不匹配(来自mysql)

这是查询:

 SELECT e1_.etapes AS etapes3, e1_.position AS position4, c0_.exercicesData_id AS Exercice_id, exo.titre as Exo, age.bornInf as ageInf, age.bornSup as ageSup, imc.bornInf as imcInf, imc.bornSup as imcSup, sexe.bornInf as sexeInf, sexe.bornSup as sexeSup

 FROM ContrainteData c0_ 

 LEFT JOIN ExerciceData e1_ ON c0_.exercicesData_id = e1_.id 
 LEFT JOIN Exercice exo ON e1_.exercice_id = exo.id 
 LEFT JOIN contraintedata_entrydata c3_ ON c0_.id = c3_.contraintedata_id 
 INNER JOIN (SELECT * FROM `entrydata` GROUP BY type_id, bornInf, bornSup) AS age ON   age.type_id = 1
 INNER JOIN (SELECT * FROM `entrydata` GROUP BY type_id, bornInf, bornSup) AS imc ON imc.type_id = 4
 INNER JOIN (SELECT * FROM `entrydata` GROUP BY type_id, bornInf, bornSup) AS sexe ON sexe.type_id = 5

 WHERE
      ( age.bornSup >= 30 and age.bornInf <= 30 ) and
      ( imc.bornSup >= 20 and imc.bornInf <= 20 ) and
      ( sexe.bornSup >= 1 and sexe.bornInf <= 1 ) and
      e1_.entrainement_id = 6

 GROUP BY etapes3, position4

 ORDER BY etapes3 ASC, position4 ASC

使用queryBuilder,我已完成以下操作:

    $qb1            = $this->createQueryBuilder('c');
    $qb2            = $this->createQueryBuilder('t');


    $qb2->select( 't' )
        ->from  ( 'bonk\AppBundle\Entity\EntryData', 'en' )
        ->groupBy( 'en.type')
        ->addGroupBy( 'en.bornInf' )
        ->addGroupBy( 'en.bornSup' );


    $qb1->select( 'c' )
        ->leftJoin( 'c.exercicesData', 'e'  )
        ->leftJoin( 'e.exercice'     , 'ex' )
        ->join    ( $qb2->getDql(), 'age', 'with', 'age.type = 1' )
        ->join    ( $qb2->getQuery()->getDql(), 'imc', 'with', 'imc.type = 4' )
        ->join    ( $qb2->getQuery()->getDql(), 'sexe', 'with', 'sexe.type = 5')
        ->where   ( 'age.bornSup >= 30 and age.bornInf <= 30'                    )
        ->andWhere( 'imc.bornSup >= 20 and imc.bornInf <= 20'                    )
        ->andWhere( 'sexe.bornSup >= 1 and sexe.bornInf <= 1'                    )
        ->andWhere( 'e.entrainement = 6'                                         )
        ->groupBy ( 'e.etapes', 'ASC'                                            )
        ->addGroupBy( 'e.position', 'ASC'                                        );

    return $qb1->getQuery()->getArrayResult();

我有以下错误:

      "[Semantical Error] line 0, col 116 near 'SELECT t FROM': Error: Class 'SELECT' is not defined "

1 个答案:

答案 0 :(得分:0)

我终于成功获得了一个mysql视图,该视图由doctrine和DQL Query中的假实体调用。

在sql上创建一个视图,只需执行以下行:

"create view VIEWNAME YOUQUERY"
在我的例子中

"create view entrydataView SELECT * FROM `entrydata` GROUP BY type_id, bornInf, bornSup"