【问题标题】:How to paginate custom query result in cakephp如何在cakephp中对自定义查询结果进行分页
【发布时间】:2015-08-20 06:08:20
【问题描述】:

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

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

$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);

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

$resultset = $this->Asin->query("SELECT * FROM products INNER JOIN asins ON products.id=asins.id ORDER BY products.id");

如何添加分页?

【问题讨论】:

  • 请检查提供的答案是否有用。谢谢。

标签: php mysql cakephp pagination cakephp-2.0


【解决方案1】:

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

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

....

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

然后终于在控制器动作中

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

【讨论】:

  • 这不适用于连接,我没有用普通查询检查。
【解决方案2】:

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

【讨论】:

  • 没有。我需要知道是否可以在没有任何模型帮助的情况下对上述查询的结果集进行分页
猜你喜欢
  • 1970-01-01
  • 2020-01-11
  • 2021-01-30
  • 1970-01-01
  • 2019-09-07
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
相关资源
最近更新 更多