如何向' WHERE'动态添加额外条件? TYPO3数据库查询中的子句好吗?新的TYPO3版本8文档说明了如何进行固定查询,而不是变量查询。
过去,我可以创建一个SQL语句并动态修改它,如下所示:
if (condition) {
$strWhere = 'some SQL';
} else {
$strWhere = 'same SQL with extra bits';
}
$dbRes = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
"*", // SELECT ...
"tableName", // FROM ...
$strWhere , // WHERE...
etc.
我无法使用Querybuilder查看如何执行此类操作。我想要实现的是一个像这样做的表达式
if (condition) {
->where($queryBuilder->expr()->eq(... ))
}
else {
->where($queryBuilder->expr()->eq(... ))
->andWhere($queryBuilder->expr()->eq(... ))
}
任何提示都会非常感激。感谢。
答案 0 :(得分:4)
解决。我的错误在于认为“查询”构建器语句的各个部分必须汇集在一起 - 它们不会。
所以这个:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_tablename');
$queryBuilder
->select('uid', 'header', 'bodytext')
->from('tt_content')
->where(
$queryBuilder->expr()->eq('bodytext', $queryBuilder->createNamedParameter('klaus')),
$queryBuilder->expr()->eq('header', $queryBuilder->createNamedParameter('a name'))
)
->execute();
也可以分成几部分,例如:
switch ($scope) {
case 'limitfields':
$queryBuilder->select('uid','header','bodytext');
break;
default:
$queryBuilder->select('*');
break;
}
$queryBuilder
->from('tt_content')
->where(
$queryBuilder->expr()->eq('bodytext', $queryBuilder->createNamedParameter('klaus')),
$queryBuilder->expr()->eq('header', $queryBuilder->createNamedParameter('a name'))
)
->execute();
答案 1 :(得分:1)
$queryBuilder = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\ConnectionPool')->getQueryBuilderForTable('tx_igldapssoauth_config');
$expressionBuilder = $queryBuilder->expr();
$conditions = $expressionBuilder->andX();
$conditions->add(
$expressionBuilder->eq('somefield', 1)
);
$conditions->add(
$expressionBuilder->eq('someotherfield', 2)
);
$rows = $queryBuilder->select('*')
->from('tx_igldapssoauth_config')
->where(
$queryBuilder->expr()->eq('uid', 1)
)
->andWhere($conditions)
->execute()->fetchAll();