gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:06:12 24 4
gpt4 key购买 nike

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

通过这种方式,我可以对“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");

如何添加分页?

最佳答案

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

然后终于在 Controller Action 中

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

关于php - 如何在cakephp中对自定义查询结果进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30664018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com