When migrating a Zend Framework application to Doctrine 2.5 DBAL, you may encounter challenges joining subqueries. This article aims to provide a comprehensive guide to this specific issue.
The given Zend_Db query features a subquery to retrieve minimum timestamps for specific user surveys. The main query subsequently joins this subquery to fetch additional data. The goal is to replicate this functionality using Doctrine 2.5's query builder.
Initially, it was believed that Doctrine does not support joining subqueries. However, there is a workaround.
The solution is to obtain the raw SQL of the subquery and enclose it in brackets. The join syntax resembles a regular join operation. However, parameters used in the subquery must be defined in the main query.
<code class="php">$subSelect = $connection->createQueryBuilder() ->select(array('userSurveyID', 'MIN(timestamp) timestamp')) ->from('user_survey_status_entries') ->where('status = :status') ->groupBy('userSurveyID'); $select = $connection->createQueryBuilder() ->select($selectColNames) ->from('user_surveys', 'us') ->leftJoin('us', sprintf('(%s)', $subSelect->getSQL()), 'firstAccess', 'us.userSurveyID = firstAccess.userSurveyID') ->setParameter('status', UserSurveyStatus::ACCESSED) ->where('us.surveyID = :surveyID') ->setParameter('surveyID', $surveyID);</code>
This workaround allows you to join subqueries in Doctrine 2.5 DBAL. By obtaining the raw SQL of the subquery and setting its parameters in the main query, you can achieve the desired query structure.
The above is the detailed content of How to Join Subqueries with Doctrine 2 DBAL?. For more information, please follow other related articles on the PHP Chinese website!