【问题标题】:zend paginator problemzend分页器问题
【发布时间】:2010-12-04 03:55:21
【问题描述】:
我想在我的项目中使用 Zend Paginator 和原始 sql 查询(不是 Dbselect)。
我不能使用 Dbselect,因为我在主 sql 查询中有几个子查询。
从手册中我发现唯一的方法是像这样在结果数组上使用分页
$paginator = Zend_Paginator::factory($array);
但我在查询中有很多记录,这对我来说似乎是个坏主意。
有什么办法可以解决这个问题吗?
【问题讨论】:
标签:
php
zend-framework
pagination
【解决方案1】:
如果您的查询真的很复杂以至于您无法使用Zend_Db_Select,您可以编写自己的Zend_Paginator_Adapter,即not as complicated as it might sound。
您的相应类只必须实现 Zend_Paginator_Adapter_Interface 以允许您将类传递给 Zend_Paginator 构造函数。
下面是一个简单的例子——你可以把它作为一个起点...
class App_Model_ListOfItems implements Zend_Paginator_Adapter_Interface
{
/**
* @var Zend_Db_Adapter_Abstract
*/
protected $_db;
/**
* @param Zend_Db_Adapter_Abstract $db
*/
public function __construct(Zend_Db_Adapter_Abstract $db)
{
$this->_db = $db;
}
/**
* @implements Zend_Paginator_Adapter_Interface
* @return integer
*/
public function count()
{
return (int)$this->_db->fetchOne('SELECT COUNT(*) FROM <<add your query to determine the total row count here>>');
}
/**
* @implements Zend_Paginator_Adapter_Interface
* @param integer $offset
* @param integer $itemCountPerPage
* @return array
*/
public function getItems($offset, $itemCountPerPage)
{
$sql = 'SELECT <<add your columns, tables, joins and subqueries as needed>> LIMIT ' .
(int)$offset . ', ' . (int)$itemCountPerPage;
return $this->_db->fetchAll($sql);
}
}
$paginator = new Zend_Paginator(new App_Model_ListOfItems($db));
【解决方案2】:
您可以像这样在数据库选择中使用子查询:
$select = $this->_db->select();
$select->from( 'customer', array( 'id', 'first_name', 'family_name', 'company', 'phone', 'email' ) );
$select->joinLeft( 'sale', 'customer.id = sale.customer_id and sale.id in (select max( id ) from sale group by customer_id)', array( 'sale_id' => 'id', 'billing_phone', 'shipping_phone', 'billing_city', 'billing_country', 'created_on' ) );
(上面的查询返回客户姓名,以及他们最近购买的联系方式)