Paginate from within a model in CakePHP

The way I figured out how I can keep my complex find in my model without having to rewrite it a second time in the controller is by passing a $paginate boolean variable.

If $paginate is true, it returns just the options created, which can then be used in the controller’s pagination. If it’s false (meaning we don’t want to paginate), it returns the actual event results. So far this seems to be working.

In my getEvents() function (this method is in the Events model)

    if($paginate) {
        return $qOpts; // Just return the options for the paginate in the controller to use
    } else {
        $data = $this->find('all', $qOpts); // Return the actual events
        return $data;
    }

Then, in my Events/Index (events controller, index action – where I know I want pagination):

$this->Event->recursive = -1; // (or set recursive = -1 in the appModel)
$opts['paginate'] = true;

$paginateOptions = $this->Event->getEvents($opts);

$this->paginate = $paginateOptions; // Set paginate options to just-returned options
$data = $this->paginate('Event'); // Get paginate results
$this->set('data', $data); // Set variable to hold paginated results in view

Leave a Comment