在CakePHP中分页()之前在Controller中进行排序


Sorting in Controller before paginate() in CakePHP

所以我的ItemsController中有一个可爱的小索引函数:

public function index() {
        $this->Item->recursive = 2;
        $this->set('items', $this->paginate());
    }

这是因为我在afterFind上做了一堆计算(添加一个字段,并按它排序)

但我想在控制器级别上排序,这样我就可以有一个recent(),等等。如果我在afterFind级别上排序,无论控制器是什么,每次都会这样排序——所以这不好。

如何在控制器级别上排序,并且仍然能够正确使用$this->paginate()?

仅供参考以下是我的一些AfterFind:

public function afterFind($results, $primary = false){
    parent::afterFind($results, $primary);
    foreach ($results as $key => $val) {
        // my foreach logic calculating Item.score  
    }
// the stuff I should be doing on a controller-to-controller basis:
    $results = Set::sort($results, '{n}.Item.score', 'desc'); 
    return $results;
}

这就是使用分页器进行排序的方法

public function index() {
  $this->paginate = array(
    'limit' => 10,
    'order' => array( // sets a default order to sort by
      'Item.name' => 'asc'
    )
  );
  $items = $this->paginate('Item');
  $this->set(compact('items'));
}

在您看来:

<div class="sort-buttons">
  Sort by
  <?php echo $this->Paginator->sort('name', 'By Name', array('class' => 'button')); ?>
  <?php echo $this->Paginator->sort('score', 'By Score', array('class' => 'button')); ?>
  <?php echo $this->Paginator->sort('date', 'By Date', array('class' => 'button')); ?>
</div><!-- /.sort-buttons -->

或者,如果使用创建REST API,请使用查询字符串:

http://myapp.dev/items/index?sort=score&direction=desc

我的工作方式是进入控制器:

/******************************************************************
 * 
 ******************************************************************/
function admin_index() {
    $this->paginate = array(
        'News' => array(
            'order' => array(
                'News.created' =>  'DESC'
            )
        )
    );
    $data = $this->paginate('News');
    $this->set('news', $data);
}