Paginate from within a model in CakePHP

前端 未结 4 794
情深已故
情深已故 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:11

    The way I figured out how I can keep my complex find in my model without having to rewrite it a second time in the controller is by passing a $paginate boolean variable.

    If $paginate is true, it returns just the options created, which can then be used in the controller's pagination. If it's false (meaning we don't want to paginate), it returns the actual event results. So far this seems to be working.

    In my getEvents() function (this method is in the Events model)

        if($paginate) {
            return $qOpts; // Just return the options for the paginate in the controller to use
        } else {
            $data = $this->find('all', $qOpts); // Return the actual events
            return $data;
        }
    

    Then, in my Events/Index (events controller, index action - where I know I want pagination):

    $this->Event->recursive = -1; // (or set recursive = -1 in the appModel)
    $opts['paginate'] = true;
    
    $paginateOptions = $this->Event->getEvents($opts);
    
    $this->paginate = $paginateOptions; // Set paginate options to just-returned options
    $data = $this->paginate('Event'); // Get paginate results
    $this->set('data', $data); // Set variable to hold paginated results in view
    

提交回复
热议问题