paginating ad-hoc joins in CakePHP

Couple months ago, Nate published in the bakery a quick tip to do what he called ad-hoc joins in cakephp’s find()
Basically the trick was to use the joins parameter of the method find() to define the associations.
I have noticed a lot of people asking about how to paginate the results.
So This post is exactly for doing that..
I’ll be using the modified version found in the comments by Bambou
Basically His version allows to define the type of find() using a parameter called operation
just copy it to your AppModel, or the model that you want to do ad-hoc joins on:
Now for pagination to work with the new matches’ type, you’ll have to write a custom paginateCount()
copy this to your AppModel or the model in question:

  1.  
  2. function paginateCount($conditions = array(), $recursive = 0, $extra = array()) {
  3.  
  4.         $parameters = compact(conditions’);
  5.         if ($recursive != $this->recursive) {
  6.                 $parameters[recursive’] = $recursive;
  7.         }
  8.         if(isset($extra[type’]) && ($extra[type’] == matches’)) {
  9.                 $extra[operation’] = count’;
  10.                 return $this->find(matches’, array_merge($parameters, $extra));
  11.         } else {
  12.                 return $this->find(count’, array_merge($parameters, $extra));
  13.         }       
  14. }

Usage is nearly identical to the normal paginate() except that instead of doing:

  1.  $markers = $this->Marker->find(matches’, array(
  2.        operation’ => all’,
  3.         model’ => Tag’,
  4.         ’scope’ => array(Tag.tag’ => $tags)
  5.    )
  6. );

You’ll do:

  1.  array_unshift($this->paginate, matches’);
  2. $this->paginate[model’] = Tag’;
  3. $this->paginate[operation’] = all’;
  4. $this->paginate[’scope’] = array(Tag.tag’=>$tags);
  5. $result = $this->paginate();

The trick indeed is in array_unshift($this->paginate, matches’);
and has to do with how paginate() works internally ( makes the assumption/convention that the first element in the paginate array is the type )
So that’s it, hopefully this will help some misguided cakephp souls