Simple test to display records obtained by Model class in CakePHP

It is often needed to test only data structure in CakePHP. When “scaffold” cannot cover the required structure, for example, when we want to customize them with ‘GROUP BY’ or query conditions, a combination of set(compact(‘data’)) and debug($data) is generally used.

This is very quite common, but I wrote this down ’cause I was asked before.

  • Model : define relationships like belongsTo and etc.
  • Controller : add an action you need #set(compact(‘data’)) will be used here
  • View : create a .ctp file designed for the controller and its action. #debug($data) will be used here

Let’s see an example.


class Users extends extends AppModel {
    public $belongsTo = array('Group');
} ?>


class UsersController extends AppController {
    public function index() {
        $data = $this->User->find('all', array(
            'fields' => array('COUNT( AS total', 'Group.*'),
            'group' => array('')


<?php debug($data); ?>

The array structure will be shown by the ‘debug’ function, accessing http://[Your CakePHP Root]/users/.