【问题标题】:cakephp pagination and thin controllercakephp 分页和瘦控制器
【发布时间】:2015-01-20 18:43:56
【问题描述】:

我正在使用 cakephp (2.4.7) 进行开发,但在组织控制器和模型以使用分页时遇到问题。

到目前为止,我将大部分逻辑放入模型中(瘦控制器,大模型)。在那里我将结果返回给控制器,在那里我设置变量以将其显示在视图上。

但现在我想使用分页。这打破了我的概念,因为我不能在模型中使用分页。

解决此问题的最佳解决方案是什么?我不想重新组织我的整个结构,因为我需要在很多不同的动作和模型中进行分页。

例如:

控制器用户,动作朋友

public function friends($userid = null, $slug = null) {
    $this->layout = 'userprofile';      
    $this->User->id = $userid;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid User'));
    }

    $this->set('friends', $this->User->getFriendsFrom($userid));
}

用户模型,函数 getFriendsFrom($user_from).. 我在不同的操作中需要这个方法。

public function getFriendsFrom($user_from) {

    $idToFind = $user_from;

    $data = $this->FriendFrom->find('all', 
        array(
            'conditions'=>array(
                'OR'=> array(
                    array('user_to'=> $idToFind),
                    array('user_from'=> $idToFind)
                ),
                'AND' => array(
                    'friendship_status' => 1
                )
            ),
            'contain' => array('UserFrom.Picture', 'UserTo.Picture')
        )
    );

    $friendslist = array();
    foreach ($data as $i) {
        if ($i['FriendFrom']['user_from'] == $idToFind){
            $friendslist[] = $i['UserTo'];
        }
        elseif ($i['FriendFrom']['user_to'] == $idToFind){
            $friendslist[] = $i['UserFrom'];
        }
    }

    return $friendslist;
}

设计这个概念以使用分页的最佳方式是什么?

谢谢

【问题讨论】:

    标签: php cakephp pagination cakephp-2.0


    【解决方案1】:

    在Controller中用户使用cakephp分页器

    var $helpers = array('Paginator');
    

    现在你调用下面的方法

    function index() {
        $result = array(
            'recursive' => -1,
            'conditions' => array(...),
            'contain' => array(...),
            'limit' => '2'
        );
        // you can write the above code in your model
        $this->paginate = $result; 
        $users = $this->paginate('User');
    
        // Re-arrage $users 
    
        $this->set(compact('users'));
    }
    

    如果有任何问题,请告诉我。

    【讨论】:

    • 现在 $friends 中的所有用户都拥有所有其他信息(关联表)。但不是 getFriendsFrom() 的结果
    • 解释你的表结构。我认为您的 getFriendsFrom() 根据您的查询返回行。
    • 用户表与朋友操作中的许多其他表(画廊等)相关联,我只想显示朋友。但是在您的解决方案中,$friends 变量中填充了所有注册用户。我认为是因为 $this->paginate('User');
    • 我建议您先编写查询并调试查询,如果您的查询从表中返回期望记录,然后应用 cakephp Paginator 的分页帮助。请参阅以下链接book.cakephp.org/2.0/en/core-libraries/components/…
    • @Supravat,我有同样的问题。我认为 getFriendsFrom 方法正在正确返回数据。但是 $friends = $this->paginate('User'); $this->set('friends', $friends);等于 $friends = $this->User->find('all); $this->set('friends', $friends);这是错误的,因为 $friends 没有填充 getFriendsFrom..的结果。
    猜你喜欢
    • 1970-01-01
    • 2013-01-20
    • 2012-05-07
    • 2012-01-25
    • 2013-04-23
    • 2013-12-28
    • 2011-12-02
    • 2015-04-24
    • 2015-06-25
    相关资源
    最近更新 更多