如何在不使用原始SQL的直接低级查询的情况下使用SQL_CALC_FOUND_ROWS
获取Zend\Db\TableGateway
?
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) {
return $this->tableGateway->select(function (Select $select) use ($page, $perpage) {
$select
->limit($perpage)
->offset(($page - 1) * $perpage);
});
}
}
我希望获得fetchAll
中使用的同一查询中的记录总数。
答案 0 :(得分:8)
看起来Zend Framework 2.1.4支持指定量词。这使您可以在select对象中使用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;
}
}