
Containable in CakePHP
May 26, 2009I’ve see a lot of traffic to my post about Using unBindModel in CakePHP and while it is a way of cutting down the data that is returned from a query, there is now a better way. Containable behaviour
I’ve only just stumbled upon this and after having used it briefly in testing it seems like a really cool way to chain together models and yet only get the data that you want at the time.
I have used it like this to get the County that a Club is in
$this->User->contain(array(
'Club' => array(
'County'
)
));
$user = $this->User->find('first', array(
'conditions' => array(
'User.id' => 1
),
));
This query brings back an array with User data, Club data and County data. The interesting bit is the Club
[Club] => Array
(
[id] => 1
[name] => Ballymun Kickhams GAA Club
[county_id] => 2
[County] => Array
(
[id] => 2
[province_id] => 1
[name] => West Dublin
)
)
$this->User->contain(array(
‘Club’ => array(
‘County’
)
));
$user = $this->User->find(‘first’, array(
‘conditions’ => array(
‘User.id’ => 1
),
));
can be rewritten also as
$user = $this->User->find(
‘first’, array(
‘contain => array(
‘Club’ => array(
‘County’
),
),
‘conditions’ => array(
‘User.id’ => 1
),
)
);
or even shotter
# $user = $this->User->find(‘first’, array(
# ‘conditions’ => array(
# ‘User.id’ => 1
# ),
# ‘contain’ => array(‘Club.Country’)
# ));
What I would actually need in this situation is:
$user = $this->User->find(‘first’, array(
‘conditions’ => array(
‘User.id’ => 1
),
‘contain’ => array(
‘Club.name’ => array(
‘County.name’
)));
This would then give me the User, their Club and their County from different tables.