我有一个简单的查询,它选择实体并使用limit语句。我使用Doctrine NativeQuery,因为我在sql中有FIELD()函数,因此需要一个对象集合。这个查询有效。
但是,我还需要记录的总数,所以我在第一个查询中使用SQL_CALC_FOUND_ROWS。在第一个得到结果之后,我创建了另一个ResultSetMapping,另一个$nativeQuery,执行SELECT FOUND_ROWS() AS found_rows,我一直得到'1‘的总数。
$rsm = new ResultSetMapping();
$rsm->addEntityResult('\\MyCompany\\Administration\\Domain\\Model\\Applicant\\Applicant', 'a');
$rsm->addFieldResult('a', 'first_name', 'firstName');
$rsm->addFieldResult('a', 'last_name', 'lastName');
$query = $this->em->createNativeQuery('SELECT SQL_CALC_FOUND_ROWS * FROM recruitment_applicant ORDER BY FIELD(id,5,15,8,17,2,1,16,9,7,11,6,10,12,13,14,18)', $rsm);
$result = $query->getResult(); // this result is ok
$sqlCountRows = "SELECT FOUND_ROWS() AS found_rows";
$countRowsRsm = new ResultSetMapping();
$countRowsRsm->addScalarResult('found_rows', 'foundRows');
$countRowsQuery = $this->em->createNativeQuery($sqlCountRows,$countRowsRsm);
$rowsCount = $countRowsQuery->getResult();
$total = $rowsCount[0]['foundRows']; // result is '1' when it should be '16'我用了这的例子。
发布于 2013-12-17 16:07:16
FIELD()作为一个自定义的DQL函数非常容易实现:使用Doctrine\ORM\Query\AST\Functions\FunctionNode;使用
1. Read [DQL User Defined Functions](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html) and [How to Register Custom DQL Functions](http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html) on Doctrine/Symfony documentation.
2. `FIELD()` implementation:\ORM\Query\Lexer;使用Doctrine\ORM\Query\Parser;使用Doctrine\ORM\Query\SqlWalker;类字段扩展FunctionNode {私有$field = null;私有$values =数组();公共函数解析(解析器$parser) {$解析器->匹配(Lexer::T_IDENTIFIER);$解析器->匹配(Lexer::T_OPEN_PARENTHESIS);$此->字段=$解析器->算术主体();而(count($this->values) <1欧元->getLexer()->展望式‘==Lexer::T_CLOSE_PARENTHESIS’){$解析器->匹配(Lexer::T_COMMA);$this->values[] =$解析器->算术解析器();}$解析器->匹配( Lexer::T_CLOSE_PARENTHESIS);}公共函数getSql(SqlWalker $sqlWalker) { $values =数组();{ $values[] =$values[]->调度($sqlWalker);}返回sprintf(‘字段(%s,%s)',$this->字段->调度($sqlWalker),内爆( ',’,$values);}
COUNT(*)查询,可以很容易地克隆原始查询,并使用CountWalker从select查询创建计数查询。发布于 2013-12-17 15:52:05
我发现了问题的原因: Symfony2分析器,查询部分,显示了总共执行的22个查询。我的第一个查询在一行中第三次运行,第二个查询返回行数的查询被执行第13行。如果在第一个查询之后立即运行SQL_CALC_FOUND_ROWS,则SELECT FOUND_ROWS()可以工作。
https://stackoverflow.com/questions/20632441
复制相似问题