Cakephp自定义查询与分页?

时间:2014-03-24 07:50:59

标签: php pagination cakephp-2.0

我正在开发一个Web应用程序,为此我需要进行自定义查询。我在下面给出了我的代码示例:

function index() {
        $this->layout = 'reserved';
        $info = $this->Auth->user();
        $user_id = $info["id"];
        $club_info = $this->Club->find('first', array('conditions' => array('Club.user_id' => $user_id)));
        if ($club_info) {

            $club_id = $club_info['Club']['id'];
            $club_name = $club_info['Club']['club_name'];
            $this->set(compact('user_id', 'club_id', 'club_name'));
            $clubTables =$this->ClubTable->query("SELECT *FROM club_tables ClubTable LEFT JOIN categories Category ON ClubTable.category_id=Category.id LEFT JOIN deals Deal ON ClubTable.id=Deal.club_table_id AND ClubTable.club_id='".$club_id."' AND ClubTable.status='approved' ORDER BY Deal.status DESC");
            $this->set('clubTables', $clubTables);
        } else {
            $this->set('clubTables', false);
        }
    }

一切正常,但我无法添加分页。任何想法,我怎样才能添加分页?

3 个答案:

答案 0 :(得分:1)

你应该考虑使用带有Contain选项的find()方法在Cakephp中进行查询,你可以在这里查看如何使用分页http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html

答案 1 :(得分:0)

要做到这一点,你不能使用蛋糕的魔力。这是因为您正在编写自定义查询,并且蛋糕的ORM可以理解地不知道如何支持不一定适合其模型结构的任意查询。相反,您需要自己管理分页。在您的情况下,这意味着您的查询中使用LIMITOFFSET进行旧式查询管理。有关如何在互联网上执行此操作的大量指南,因为在框架变得简单之前我们必须执行此操作多年。这是一篇讨论这个问题的帖子:

Simple PHP Pagination script

答案 2 :(得分:0)

在您的模型中

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

在你的控制器中

public function index()
{
    $this->Offre->recursive = 0;

    $this->paginate = array('Offre'=>array('limit'=>10));

    $this->set('offres', $this->paginate('Offre'));
}