在CakePHP中使用带有自定义模型方法的分页


Using pagination with a custom model method in CakePHP

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

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()方法。希望我能做到。

干杯。

是。

//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);
}

解释:

基本上,您只需添加另一个参数(我通常只称之为"paginate"),如果在模型中为true,则不返回查找结果,而是返回动态创建的参数-然后使用这些参数在控制器中进行分页。

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