Search code examples
phpmysqlzend-frameworkzend-db

how to make group by optional in zend framework?


i have a fetchAll function in 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);
}

and i can call this function $this->fetchAll('field = 1', null, 10);

i can $order to null and the query will work just fine but not the $group for some reason.

How can i make it so that the group is optional and goes in only if i sat it to something?

thanks


Solution

  • The methods are chained so you can split it up:

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

    Every method in the chain (from, where, order, etc) returns an instance of Zend_Db_Select. So every time you call one of those methods you can immediately follow it up with another method call from that same class.

    These code blocks are identical:

    // 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);
    

    You can see why chaining is preferred. Note: the assignment ($select =) is mostly superflous in the non-chain example, I only left it in to show the clunkyness.