首页 > 解决方案 > Doctrine\DBAL\DBALException:平台 mssql 不支持限制查询中的偏移值

问题描述

错误非常简单。我使用 Symfony 4 和 MSSQL Server 作为数据库服务器,配置如下:

driver: 'sqlsrv'
url: 'mssql://username:password@host:1433/db'

当我使用 setFirstResult() 时发生错误

$entityManager->createQueryBuilder()->select('u')->from(UserEntity::class, 'u')
        ->setFirstResult(20)->setMaxResults(20)
        ->getQuery()->getArrayResult();

错误信息:

In AbstractPlatform.php line 3359:
[Doctrine\DBAL\DBALException]                                    
Platform mssql does not support offset values in limit queries.

痕迹:

 () at /var/www/html/ple-studio/vendor/doctrine/dbal/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php:3359
 Doctrine\DBAL\Platforms\AbstractPlatform->modifyLimitQuery() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php:545
 Doctrine\ORM\Query\SqlWalker->walkSelectStatement() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php:42
 Doctrine\ORM\Query\Exec\SingleSelectExecutor->__construct() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php:278
 Doctrine\ORM\Query\SqlWalker->getExecutor() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:398
 Doctrine\ORM\Query\Parser->parse() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:283
 Doctrine\ORM\Query->_parse() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:295
 Doctrine\ORM\Query->_doExecute() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:967

对我有用的解决方案是手动使用原始查询:

$sql .= ' OFFSET ' . $offset . ' ROWS FETCH NEXT ' . $itemPerPage . ' ROWS ONLY';

但是这个解决方案会破坏使用 ORM 的目的,如果我切换到 MySQL,它将无法工作。

解决上述错误的正确方法是什么?

标签: phpdoctrine-ormdoctrinesymfony4

解决方案


看起来您可能需要更改配置驱动程序值,如下所示:

driver: 'mssql'

https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url


推荐阅读