首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在cakephp中对自定义查询结果进行分页

问如何在cakephp中对自定义查询结果进行分页
EN

Stack Overflow用户
提问于 2015-06-05 18:16:07
回答 2查看 8.1K关注 0票数 7

我正在做一个cakephp项目,并且是cakephp的新手。正如标题中提到的,我需要对mysql查询的结果集进行分页,以便在视图中显示它们。

通过这种方式,我可以对"Asin“模型的结果进行分页。

代码语言:javascript
复制
$this->paginate =array('Asin'=>array(
            'fields' => array('sku','fnsku'),
            'conditions' => $marketplace,
            'page' => 1, 'limit' => 20,
            'order' => array('Asin.asin' => 'asc')
        )
$data = $this->paginate('Asin',$criteria);

我还需要一种方法来对以下查询的结果集进行分页。

代码语言:javascript
复制
$resultset = $this->Asin->query("SELECT * FROM products INNER JOIN asins ON products.id=asins.id ORDER BY products.id");

如何添加分页?

EN

回答 2

Stack Overflow用户

发布于 2015-06-05 19:38:51

CakePHP使用两种方法来管理分页查询,即分页和paginateCount,它们分别用于获取页面数据和总记录数。要让分页处理您的自定义查询,我们需要在我们的模型文件中实现上述两个函数,在模型文件中,您希望使用分页来处理自定义查询。

代码语言:javascript
复制
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {    
    $recursive = -1;

    // Mandatory to have
    $this->useTable = false;
    $sql = '';

    $sql .= "Your custom query here just do not include limit portion";

    // Adding LIMIT Clause
    $sql .= (($page - 1) * $limit) . ', ' . $limit;

    $results = $this->query($sql);

    return $results;
}

……

代码语言:javascript
复制
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {

    $sql = '';

    $sql .= "Your custom query here just do not include limit portion";

    $this->recursive = $recursive;

    $results = $this->query($sql);

    return count($results);
}

然后,最后在控制器操作中

代码语言:javascript
复制
// Do not forgot to set this, not sure why
$this->Asin->recursive = 0;

// Setting up paging parameters
$this->paginate = array('Asin'=>array('limit'=>5));

// Getting paginated result based on page #
$this->set('userData', $this->paginate('Asin'));
票数 5
EN

Stack Overflow用户

发布于 2015-06-05 18:28:32

如果您正在使用任何关联关系模型,那么它是非常简单的http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30664018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档