CakePHP: Pagination with Containable

Richard's picture

Took me a little while to work this out so I'm blogging it here in the hopes it will help someone in the future:

Need to Contain your Paginated data?

in your controller:

$this->paginate = array(
	"contain"=>array(
		// usual contain array
	)
);
 
$this->set("data", $this->paginate("Model"));

For example, to bring back and paginate a User (id, first_name, last_name) and their Title (Mr, Mrs, etc.):

/app/users_controller.php

$this->paginate = array(
	"contain"=>array(
		"id", "first_name", "last_name",
		"Title"=>array(
			"name"
		)
	)
);
 
$this->set("data", $this->paginate("User"));

Happy Baking! :-)

Comments

Anonymous's picture

Well Done! Thanks for posting

Well Done!
Thanks for posting the code.
It consumed a lot of time searching to use containable with pagination.

Richard's picture

Oops! You're absolutely right

Oops! You're absolutely right - good eyes! Fixed it. Thanks :-)

Anonymous's picture

bug?

change:
$this->paginate(array(
to:
$this->paginate=array(
seems to be a bug (I run cake 1.2)

Anonymous's picture

not a bug

this is what i do and it works.
$this->paginate('Model', $conditions);
set up your contain fields in var $paginate at the top of your controller.
var $paginate = array(        'limit' => 100,        'conditions'=>array(),        'contain'=>array('Model2'=>array(                         'conditions'=>array(),                         'Model3', 'Model4.field4', 'etc'                         ),                                 'order'=>array(),            );

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options