Cakephp Paginate Find

时间:2013-08-22 12:47:00

标签: cakephp pagination

我想列出给定用户的帖子。它工作但分页不准确。

我的代码如下

public function index($userid = null) {

     if ($this->Post->exists($userid)) {

        $this->set('posts',$this->Post->find('all',array('conditions'=>array('user_id'=>$userid))), 
            $this->paginate());

        } else
        {

        $this->Post->recursive = 0;
        $this->set('posts', $this->paginate());
    }

结果给出了正确的列表 - > 3个帖子,但是分页器显示页码1和2

你能帮帮我吗? 谢谢

3 个答案:

答案 0 :(得分:3)

请参阅文档

问题中的代码非常混乱。

找到

find方法只有两个参数:

  

find(string $ type ='first',array $ params = array())

第三个参数(调用paginate的结果)未被使用并将被忽略 - 但将根据paginate调用中使用的条件设置分页助手的视图变量 - 没有使用任何条件。

无法对查找调用的结果进行分页 - 这样做可以重新调整代码以调用paginate而不是find。

PAGINATE

paginate方法只是proxypaginator component - 它可以通过多种方式使用,这个方法(控制器代码示例):

  

$这 - >分页($条件)

问题中案例的最合适用法是,完整的行动代码应该类似于:

public function index($userId = null) {
    $conditions = array();
    if ($userId) {
        $conditions['Post.user_id'] = $userId;
    }
    $this->set('posts',$this->paginate($conditions));
}

请注意,从逻辑上讲,如果请求的用户ID不存在,则响应应该是空白 - 而不是一切。

答案 1 :(得分:1)

我很确定paginate的条件现在可以这样工作。

如果要为分页设置条件,则应按如下方式进行:

$this->paginate = array('conditions' => array('Post.user_id' => $userid)));
$this->set('posts', $this->paginate());

是的,存储在$posts(视图中)的结果将是正确的,因为您为其分配了正确的查找结果,同时您没有任何条件地对帖子模型进行了分页。

答案 2 :(得分:0)

首先,您要检查帖子是否存在但是使用$userid。您是否尝试查看“如果用户存在,获取该用户的帖子,或者获取所有用户的帖子”?正如您现在所说的那样,假设您拥有$userid = 159,但max Post.id in your database is 28,那么条件无法满足,因为它正在检查是否存在Post with the id = 159存在,它没有。

其次,你的条件是错误的。您正在执行查找,然后执行分页,这是两个单独的查询。条件正在查找查询上实现,但不在分页上实现,但您只显示查找结果。

public function index($userid = null) {
    // setting recursive outside of if statement makes it applicable either way
    $this->Post->recursive = 0;

    // check if user exists
    if ($this->Post->User->exists($userid)) {
        // get posts for user
        $this->set('posts', $this->paginate('Post', array('Post.user_id' => $userid));
    }
    else{
        // get all posts
        $this->set('posts', $this->paginate('Post'));
    }    

} // end index function
相关问题