2012-05-30 11 views
3

我有一個fetchAll功能的Zend:如何在zend框架中使用可選組合?

public function fetchAll($where = 1, $order = null, $limit = null, $group = null, array $fields = null) 
{ 
    $where = (null == $where) ? 1 : $where; 


    $fields = (!isset($fields)) ? '*' : $fields; 

    $select = $this->db->select() 
         ->from("table", $fields) 
         ->where($where) 
         ->order($order) 
         ->group($group) 
         ->limit($limit, $offset); 
    echo $select; exit; 
    $result = $this->db->fetchAll($select); 
    return $this->getResultObjects($result); 
} 

,我可以調用這個函數$this->fetchAll('field = 1', null, 10);

我可以$order to null和查詢將工作得很好,但不是由於某種原因$group

我該如何使它成爲可選的組合,並且只有當我坐在某個位置時才進去?

感謝

回答

4

的方法鏈接起來,所以你可以把它分解了起來:

$select = $this->db->select() 
    ->from("table", $fields) 
    ->where($where); 
    ->order($order) 
    ->limit($limit, $offset); 

if ($group) { 
    $select->group($group); 
} 

$result = $this->db->fetchAll($select); 
return $this->getResultObjects($result); 

鏈(fromwhereorder等),每個方法返回的Zend_Db_Select一個實例。因此,每次調用其中一種方法時,都可以立即使用來自同一類的另一種方法調用。

這些代碼塊是相同的:

// With chaining 

$select = $this->db->select() 
    ->from("table", $fields) 
    ->where($where); 
    ->order($order) 
    ->limit($limit, $offset); 

// No chaining 

$select = $this->db->select(); 
$select = $select->from("table", $fields); 
$select = $select->where($where); 
$select = $select->order($order); 
$select = $select->limit($limit, $offset); 

你可以看到爲什麼鏈接是首選。注意:作業($select =)在非鏈式例子中大部分是非常誇張的,我只留下它來顯示笨重。

+0

很感謝,它的工作 – Patrioticcow

2

你可以做這樣的事情:

$select = $this->db->select() 
        ->from("table", $fields) 
        ->where($where) 
        ->order($order) 
        ->limit($limit, $offset); 

if(!empty($group)){ 
    $select->group($group) 
} 

這工作,因爲到你調用execute主義將不會執行你的查詢。所以在那之前你可以繼續構建查詢。

Doh,我以爲你的問題是關於教義。但是,顯然它與ZendDb以類似的方式工作。見Mike B的回答。