看起来 Zend Framework 2.1.4 支持指定量词。这使您可以在选择对象中使用 SQL_CALC_FOUND_ROWS。我确实发现难以解决的一件事是,如果您没有指定表,Zend 的 Zend\Db\Sql\Select 类将不会为您生成正确的 SQL。这在执行后续选择以检索 FOUND_ROWS() 时会出现问题。我在下面更新了您的代码以包含我将使用的内容。我已经将我的项目实现合并到您的代码中,所以如果某些东西不起作用,可能是因为我输入了错误的东西,但总的来说它对我有用(不像我想要的那样可取)。
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;
class ProductTable {
protected $tableGateway;
/**
* Set database gateway
*
* @param TableGateway $tableGateway - database connection
* @return void
*/
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* Fetch all products
*
* @param integer $page - page of records
* @param integer $perpage - records per page
* @return void
*/
public function fetchAll($page = 1, $perpage = 18) {
$result = $this->tableGateway->select(function (Select $select) use ($page, $perpage) {
$select
->quantifier(new Expression('SQL_CALC_FOUND_ROWS'))
->limit($perpage)
->offset(($page - 1) * $perpage);
});
/* retrieve the sql object from the table gateway */
$sql = $this->tableGateway->getSql();
/* create an empty select statement passing in some random non-empty string as the table. need this because Zend select statement will
generate an empty SQL if the table is empty. */
$select = new Select(' ');
/* update the select statement specification so that we don't incorporate the FROM clause */
$select->setSpecification(Select::SELECT, array(
'SELECT %1$s' => array(
array(1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '),
null
)
));
/* specify the column */
$select->columns(array(
'total' => new Expression("FOUND_ROWS()")
));
/* execute the select and extract the total */
$statement = $sql->prepareStatementForSqlObject($select);
$result2 = $statement->execute();
$row = $result2->current();
$total = $row['total']';
/* TODO: need to do something with the total? */
return $result;
}
}