gpt4 book ai didi

php - 使用 doctrine 2 DBAL 加入子查询

转载 作者:可可西里 更新时间:2023-11-01 06:31:41 25 4
gpt4 key购买 nike

我正在重构 Zend Framework 2 应用程序以使用 doctrine 2.5 DBAL 而不是 Zend_DB (ZF1)。我有以下 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);

这导致以下 MySQL 查询:

SELECT `us`.`userSurveyID`, 
// More columns from main query `us`
`firstAccess`.`timestamp` AS `dateFirstAccess`
FROM `user_surveys` AS `us`
LEFT JOIN (
SELECT `user_survey_status_entries`.`userSurveyID`,
MIN(timestamp) AS `timestamp`
FROM `user_survey_status_entries`
WHERE (status = 20)
GROUP BY `userSurveyID`
) AS `firstAccess` ON us.userSurveyID = firstAccess.userSurveyID
WHERE (us.surveyID = '10')

我不知道如何使用 doctrine 2.5 查询生成器加入子查询。在主查询中,我需要从子查询中选择列。

我已阅读 here该学说不支持加入子查询。如果仍然如此,我可以使用 doctrine DBAL 的 SQL 查询生成器以另一种方式编写此查询吗?原生 SQL 对我来说可能不是一个好的解决方案,因为这个查询将在代码的后面动态扩展。

最佳答案

我通过调整此 DQL example 找到了解决方案到 DBAL。诀窍是获取子查询的原始 SQL,将其括在括号中,然后加入它。子查询中使用的参数必须在主查询中设置:

重要它是 connectioncreateQueryBuilder 而不是实体管理器之一。

$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);

关于php - 使用 doctrine 2 DBAL 加入子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com