Home    Articles


ZF2 Select from table with COUNT and Group By


Here is an example of COUNT and GROUP BY select in Zend Framework 2.

I will just paste the code as i use it, you can change whatever you want to be more on your needs.

Let's assume we have some "orders" table with a county column and we need to count orders in each county.

$this->db->select = new \Zend\Db\Sql\Select();
$select =  $this->db->select
                            ->columns(array('county','orders'=>new \Zend\Db\Sql\Expression('COUNT(id)')))
$result = $this->fetchAll($select);

// fetch All method
public function fetchAll( $select = '') {
        if(is_object($select)) {
            $sql = $this->db->select->getSqlString( $this->db->getPlatform());
            $statement = $this->db->createStatement( $sql );
            $result = $statement->execute()->getResource()->fetchAll();
            return $result;
return false;