2009-10-06 147 views
1

我想在我的項目中使用Zend Paginator與原始sql查詢(而不是Dbselect)。 我無法使用Dbselect,因爲我在主sql查詢中有幾個子查詢。 從手冊我發現的唯一辦法就是使用分頁導致陣列上這樣zend paginator問題

$paginator = Zend_Paginator::factory($array); 

,但我在查詢中有很多的記錄,它看起來像一個壞主意給我。 有什麼辦法可以解決這個問題嗎?

回答

8

如果您的查詢是真的複雜,你不能使用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)); 
+0

謝謝,這是一個很好的答案 – mik 2009-10-07 06:06:19

1

您可以使用子查詢的數據庫選擇這樣的:

$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')); 

(上面的查詢將返回客戶名稱,再加上從他們最近購買的詳細聯繫方式)