In building a CakePHP app to learn the framework I’d been searching for about a day for the best way to retrieve data from related models. I came across the recursive attribute which returns all related data to a given depth. Using this appears to be hugely wasteful as the same data is likely to be fetched many times over so I continued to look for a better way.

I eventually found the containable behaviour buried away in the manual. After reading through a few times to get my head around the concept, it seems to be the answer to all my CakePHP worries.

You simply tell it which models to pull in at each step so you only retrieve the data you ask for. A bit of effort here will save a lot of database requests.

$this->Game->contain(array(
  'Character' => array(
    'User' => array(
      'fields' => 'username'
    )
  ),
  'Post' => array(
    'Character' => array(
      'User' => array(
        'fields' => 'username'
      )
    )
  )
));

I love CakePHP. There, I said it.