Paginate from within a model in CakePHP

前端 未结 4 788
情深已故
情深已故 2020-12-01 11:25

I have a function in my Event model called getEvents - you can pass limit, start and end dates, fields,

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 12:15

    The paginate() model method does not accept the same parameters as a find(). Specifically, find() wants an array of options, but paginate() wants every option passed individually. See Custom Query Pagination in the CakePHP book.

    So, instead of:

    $data = $this->paginate($qOptions);
    

    You want something like:

    $data = $this->paginate($qOptions['conditions'], $qOptions['fields'], ...);
    

    EDIT

    Custom model pagination isn't a function that you call. It's a function that you need to implement and will be called by the CakePHP framework. In the example in your question you are trying to manually call $this->paginate(...) from somewhere in your model. That doesn't work. Instead, do this.

    In your model, implement the paginate and paginateCount methods.

    function paginate($conditions, $fields, ...)
    {
        // return some data here based on the parameters passed
    }
    
    function paginateCount($conditions, ...)
    {
        // return some rowcount here based off the passed parameters
    }
    

    Then, in your controller you can use the standard pagination functions.

    function index()
    {
        $this->paginate = array('MyModel' => array(
            'conditions' => array(...),
            'fields' => array(...),
        ));
    
        $this->set('myobjects', $this->paginate('MyModel'));
    }
    

    Now, the Controller::paginate() function will grab the conditions and other data from the Controller::paginate parameter and, instead of passing it to your Model::find it will pass it to your custom Model::paginate() and Model::paginateCount() functions. So, the data that is returned is based on whatever you do in those two methods and not based on a standard find(). }

提交回复
热议问题