在 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中文网其他相关文章!