Search code examples
cakephpcontrollermodelscontainable

CakePHP and Containable


Let me start out by saying I've tried to read the CakePHP book as much as I can for this particular topic, and for whatever reason, I just cannot figure this out.

I have a few models:

Person

  • each person can have many jobs
  • each job has one branch and each branch belongsTo one city.

At first I was relying on recursive, but its not customizable enough (obviously) do get the data that I want.

https://github.com/jwg2s/temp

I either get WAY too much data in my output array, or hardly any at all.. I just can't figure this containable out, and if I could see an example of what I'm trying to do it would be great...

Thanks


Solution

  • since you've read the Cookbook up and down I won't go through all the basic details with you and just try to explain how to use the containable.

    You can use the containable with the find-functions from your models. Either from your controller or directly from your model.
    Most of the time I use the controller so I will give you an example how you would do it from there. I also try to use your specific example, so you have something to work with.

    /app/controllers/people_controller.php
    
    function index() {
        //I like to write a separate array for fields and contain
        $fields = array(
            'name',
            'birthday',
            'gender'
        );
    
        /* It's important to know, that the fields will not get included into the
         * contain-array unless it's an associated model! */
        $contain = array(
            'Job' => array(
                //within another array you define the next level of contain
                'Branch' => array(
                    //you get the deal...
                    'City'
                ),
                //if you only need specific fields you can define this here like this:
                'fields' => array('title', 'date', 'salary'),
                //or order them directly!
                'order' => 'Job.salary DESC'
            )
        );
    
        //we now to our find-fall with our 2 arrays for the fields and the contain
        //every option (like fields or order) can be used in the containable
        $people = $this->Person->find('all', array('contain' => $contain, 'fields' => $fields));
    }
    

    I hope this helped you in understanding containable a little more.