【问题标题】:Using pagination with a custom model method in CakePHP在 CakePHP 中使用带有自定义模型方法的分页
【发布时间】:2012-07-12 21:27:45
【问题描述】:

我正在设置分页以显示属于用户帐户中的图像列表。这就是我的控制器中的内容:

class UsersController extends AppController {

    public $paginate = array(
        'limit' => 5,
        'order' => array(
            'Image.uploaded' => 'DESC'
        )
    );

    // ...

    public function images() {
        $this->set('title_for_layout', 'Your images');

        $albums = $this->Album->find('all', array(
            'conditions' => array('Album.user_id' => $this->Auth->user('id'))
        ));
        $this->set('albums', $albums);

        // Grab the users images
        $options['userID'] = $this->Auth->user('id');
        $images = $this->paginate('Image');
        $this->set('images', $images);
    }

    // ...

}

它可以工作,但在我实现这个分页之前,我在我的Image 模型中有一个自定义方法来获取用户图像。这里是:

public function getImages($options) {
    $params = array('conditions' => array());

    // Specific user
    if (!empty($options['userID'])) {
        array_push($params['conditions'], array('Image.user_id' => $options['userID']));
    }

    // Specific album
    if (!empty($options['albumHash'])) {
        array_push($params['conditions'], array('Album.hash' => $options['albumHash']));
    }

    // Order of images
    $params['order'] = 'Image.uploaded DESC';
    if (!empty($options['order'])) {
        $params['order'] = $options['order'];
    }

    return $this->find('all', $params);
}

有没有办法可以使用这个getImages() 方法而不是默认的paginate()?我可以在文档中找到最接近的内容是“自定义查询分页”,但我不想编写自己的查询,我只想使用 getImages() 方法。希望我能做到。

干杯。

【问题讨论】:

    标签: php cakephp model


    【解决方案1】:

    是的。

    //controller
    $opts['userID'] = $this->Auth->user('id');
    $opts['paginate'] = true;
    $paginateOpts = $this->Image->getImages($opts);
    $this->paginate = $paginateOpts;
    $images = $this->paginate('Image');
    
    
    //model
    if(!empty($opts['paginate'])) {
        return $params;
    } else {
        return $this->find('all', $params);
    }
    

    说明:

    基本上,您只需添加另一个参数(我通常将其称为“分页”),如果它在模型中为真,则无需传回查找的结果,而是传回动态创建的参数 - 然后您用于在控制器中进行分页。

    这使您可以继续将所有模型/数据库逻辑保留在模型中,并且只需在模型根据您发送的选项构建所有复杂参数后使用控制器进行分页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      相关资源
      最近更新 更多