Join subquery with doctrine 2 DBAL

前端 未结 3 1785
谎友^
谎友^ 2020-12-03 08:24

I\'m refactoring a Zend Framework 2 application to use doctrine 2.5 DBAL instead of Zend_DB (ZF1). I have the following Zend_Db query:

$subS         


        
3条回答
  •  伪装坚强ぢ
    2020-12-03 09:01

    I've found a solution by adapting this DQL example to DBAL. The trick is to get the raw SQL of the subquery, wrap it in brackets, and join it. Parameters used in the subquery must be set in the main query:

    $subSelect = $connection->createQueryBuilder()
        ->select(array('userSurveyID', 'MIN(timestamp) timestamp'))
        ->from('user_survey_status_entries')
        // Instead of setting the parameter in the main query below, it could be quoted here:
        // ->where('status = ' . $connection->quote(UserSurveyStatus::ACCESSED))
        ->where('status = :status')
        ->groupBy('userSurveyID');
    
    $select = $connection->createQueryBuilder()
        ->select($selectColNames)
        ->from('user_surveys', 'us')
        // Get raw subquery SQL and wrap in brackets.
        ->leftJoin('us', sprintf('(%s)', $subSelect->getSQL()), 'firstAccess', 'us.userSurveyID = firstAccess.userSurveyID')
        // Parameter used in subquery must be set in main query.
        ->setParameter('status', UserSurveyStatus::ACCESSED)
        ->where('us.surveyID = :surveyID')->setParameter('surveyID', $surveyID);
    

提交回复
热议问题