Cakephp自定义查询分页


Cakephp custom query pagination

我试图在Cake中使用自定义查询,然后用下面的代码对结果进行分页:

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

我试着:

$petitions = $this->paginate($query);

不起作用。我们有办法做到吗?

OK,我还不够清楚:我需要使用从自定义查询中获取的变量数组进行分页,所以我可以在视图中使用它进行分页。有简单的方法吗?下面是我的代码:

function index() {
        if ($this->Session->read('Auth.User.group_id') != 1) {
            $commune_id = $this->Session->read('Auth.User.commune_id');
            $commune_id = $this->Petition->Commune->findbyId($commune_id);
            $commune_id = $this->Petition->Commune->find('all',array('conditions' => array('group' => $commune_id['Commune']['group'])));
            $count = count($commune_id);
            $i=1;
            $sql = "SELECT * FROM `petitions` WHERE `commune_id` = ";
            foreach($commune_id as $commune_ids){
                if($i==1){
                $sql .= $commune_ids['Commune']['id'];
                }else{
                $sql .= " OR `commune_id` = ".$commune_ids['Commune']['id'];
                }
            /*if($i != $count){
            $this->paginate = array(
                'or' => array(
                    array('Petition.commune_id LIKE' => $commune_ids['Commune']['id'] . ","),
                    //array('Petition.commune_id LIKE' => "," . $commune_ids['Commune']['id'] . ",")
                    ),
                'limit' => 10
            );
            }*/
            $i++;
            }
            $query = $this->Petition->query($sql);
        }
        $this->Petition->recursive = 0;
        $petitions = $this->paginate();
        $this->set('petitions', $petitions);
    }

你真的需要阅读蛋糕书中的分页部分:

function index() {
    $conditions = array();
    if ($this->Auth->user('group_id') != 1) {
        $commune_id = $this->Petition->Commune->findById($this->Auth->user('commune_id'));
       $conditions['Petition.id'] = $this->Petition->Commune->find('list',array(
            'fields'=>array('id','id')
            'conditions' => array('group' => $commune_id['Commune']['group'])
        ));
    }
    $this->Petition->recursive = 0;
    $petitions = $this->paginate('Petition',$conditions);
    $this->set('petitions', $petitions);
}

之类的

分页不是这样工作的您需要用您的条件等填充$this->validate然后直接使用$this->paginate()

看到http://book.cakephp.org/view/1232/Controller-Setup

如果真的(!)有必要的话,还请注意关于自定义查询部分的章节。