Thursday, August 14, 2014

Cakephp code with Count(*) AS Total

1. Create table with name : `activities`

CREATE TABLE IF NOT EXISTS `activities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day` varchar(50) NOT NULL,
  `date` date NOT NULL,
  `week` varchar(10) NOT NULL,
  `month` varchar(10) NOT NULL,
  `year` varchar(10) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4976

2. Data Sample : http://pastebin.com/3F41jEpU

3. Create function index in ActivitiesController

class ActivitiesController extends AppController {

    public function index() {
        $this->Activity->recursive = 0;        
        $activities = $this->Activity->find('all', array(
            'fields' => array('Activity.year', 'COUNT(*) AS total'),
            'group' => 'year',
            'order' => array('Activity.year' => 'DESC'),           
        ));       
        $this->set(compact('activities'));
    }


4. Create view for index.ctp

<table cellpadding="0" cellspacing="0">   
        <tr>
            <th><?php echo 'Year'; ?>&nbsp;</th>
            <th><?php echo 'Total'; ?>&nbsp;</th>              
        </tr>
        <?php foreach ($activities as $activity): ?>
            <tr>
                <td><?php echo h($activity['Activity']['year']); ?>&nbsp;</td>
                <td><?php echo h($activity[0]['total']); ?>&nbsp;</td>              
            </tr>
        <?php endforeach; ?>
    </table>

Output: