CakePHP: Paginate with Deep Associations

Got some CakePHP models with deep associations that you need to pull into the data that you display when you paginate them? This used to be a royal pain in the butt, and pretty much required custom pagination, but no more!


$this->paginate = array(
    'Customer' => array(
        'contain' => array(
$this->set('customers', $this->paginate('Customer'));

All you need to do for this to work? Make sure you have your associations defined, and add the Containable behavior to each of the models in question. It works flawlessly, and can go as deep as you need, and retrieve just the fields you need. I haven’t tested sorting on deep relationships yet, but I don’t think that works, because of the way Cake does its queries. But still, this is better than nothing.

%d bloggers like this: