Archive for May 26th, 2009

h1

Containable in CakePHP

May 26, 2009

I’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
                )

        )