为什么我在 CakePHP 2.x 中得到 'Call to undefined method PaginatorComponent::sort()'?

Why am I getting 'Call to undefined method PaginatorComponent::sort()' in CakePHP 2.x?

我刚开始学习 PHP,cakePHP,我无法对我的页面进行排序。 我的控制器如下;

public $helpers = array('Html', 'Form', 'Flash', 'Paginator');
public function index() 
{
    $this->Post->recursive = 0;
    $this->paginate = array ('limit' => 5);
    $this->set('posts', $this->paginate());
    $this->set('posts', $this->Post->find('all'));
    echo $this->Paginator->sort('id');
}

Paginate 工作正常,但对于排序,我收到如下致命错误

调用未定义的方法PaginatorComponent::sort()

也找不到与错误相关的任何内容。它可能真的很基础,但它真的会帮助我了解更多,我想了解更多!任何帮助将不胜感激。 提前致谢!

更新:

我在索引视图中添加了以下代码,

<th><?php echo $paginator->sort('Id', 'id'); ?></th>

但现在我收到以下错误 在 null 时调用成员函数 sort()

我相信您正在尝试设置分页默认值。这样做的正确方法是在您的控制器中定义:

public $paginate = array(
    'order' => array(
        'Post.id' => 'desc'
    )
);

或在行动中:

$this->paginate = array (
   'limit' => 5,
   'order' => array(
        'Post.id' => 'desc'
    )
);

您的索引操作应如下所示:

public function index() {
    $this->Post->recursive = 0;
    $this->paginate = array (
       'limit' => 5,
       'order' => array(
           'Post.id' => 'desc'
       )
    );
    $this->Paginator->settings = $this->paginate;
    $this->set('posts', $this->paginate());
}

在您看来,CakePHP 2.x 的正确语法是

<?php echo $this->Paginator->sort('id'); ?>

在我的索引中()

$this->paginate = array ('limit' => 5);

稍后在我的索引视图中我使用了

<?php echo $this->Paginator->sort('id','Id'); ?>

语法:this->Paginator->sort('column name','label name');

而不是正常的 html 代码。它奏效了!