CakePHP 1.2 Paginate associated model

26/04/2008 Written by: Chris

Ok this took a while for me to figure out. But it is possible to override the default pagination function in CakePHP so you paginate a different model, i paginated all related articles on a tag with this example.

  1. <?php
  2.         public function paginate($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
  3.        
  4.                 if(isset($conditions['tag'])){
  5.                         $tag = $conditions['tag'];
  6.                         unset($conditions['tag']);
  7.                 }                      
  8.                 $this->hasAndBelongsToMany['Article'] = am(     
  9.                 $this->hasAndBelongsToMany['Article']
  10.                 compact('conditions', 'fields', 'order', 'limit', 'page')       
  11.                 );     
  12.                
  13.                 if(isset($tag)){
  14.                         $result = $this->findByName($tag);
  15.                 } else {
  16.                         $result = $this->findAll();
  17.                 }
  18.                
  19.                 return $result
  20.         }              
  21.        
  22.         public function paginateCount($conditions = null) {
  23.        
  24.                 if(isset($conditions['tag'])){
  25.                         $tag = $conditions['tag'];
  26.                         unset($conditions['tag']);
  27.                         $tmp = $this->hasAndBelongsToMany['Article'];   
  28.                         $this->hasAndBelongsToMany['Article']['fields'] = array('id');                 
  29.                         $this->hasAndBelongsToMany['Article'] = $tmp;
  30.                 }
  31.                 if(isset($tag)){
  32.                         $tags = $this->findByName($tag);
  33.                         $amount = count($tags['Article']);
  34.                 } else {
  35.                         $tags = $this->findAll();
  36.                         $amount= count($tags);
  37.                 }
  38.                        
  39.                 return $amount;
  40.         }       
  41. ?>

Related tags