在 Zend Framework 2 應用程式中,Zend_DB 正在替換為 Doctrine 2.5 DBAL。以下 Zend_DB 查詢示範了這一點:
$subSelect = $db->select() ->from('user_survey_status_entries', array('userSurveyID', 'timestamp' => 'MIN(timestamp)')) ->where('status = ?', UserSurveyStatus::ACCESSED) ->group('userSurveyID'); $select = $db->select() // $selectColNames contains columns both from the main query and // the subquery (e.g. firstAccess.timestamp AS dateFirstAccess). ->from(array('us' => 'user_surveys'), $selectColNames) ->joinLeft(array('firstAccess' => $subSelect), 'us.userSurveyID = firstAccess.userSurveyID', array()) ->where('us.surveyID = ?', $surveyID);
但是,使用者希望使用 Doctrine 2.5 查詢建構器加入子查詢並從主查詢中的子查詢中選擇列。不幸的是,Doctrine 不支援連接子查詢。
幸運的是,使用者可以使用 Doctrine DBAL 的 SQL 查詢建構器來編寫此查詢:
$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);
以上是如何使用 Doctrine 2 DBAL 連接子查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!