Question

How to append to contain when it's already declared?

  1. I call a regular contain/find:

    // A controller
    $this->Site->contain(array('User'));
    $site = $this->Site->find();
    
  2. I want to automatically add something to contain. I was thinking of doing this in the Model by adding to the find function... something like this:

    // Site.php Model
    function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
        if(!isset($this->containVariable) || !in_array('Box', $this->containVariable)) {
            $this->containVariable[] = 'Box';
        }
        parent::find($conditions, $fields, $order, $recursive);
    }
    

To make this work (automatically adding model Box to contain) I only need to change $this->containVariable by a function or variable that has an array of what's already in contain. In this case this would return array('User'). How to append to contain when it's already declared? Is there a variable that contains contain?

Was it helpful?

Solution

Unless someone can find another solution I've came to the conclusion that:

Unfortunately what I was trying to do seems impossible how containable is designed. I had to manually add my model to every ->contain() calls.

OTHER TIPS

I fixed perhaps a similar issue with persisting contain for multiple find calls (using cakephp 1.3). After declaring contain for a certain model, this will be set for that model:

$this->Behaviors->Containable->runtime

-where $this is some model object. 'runtime' is an array that essentially holds the contain information. So you are close I believe, but instead of:

$this->containVariable[] = 'Box'

You would have:

$this->Behaviors->Containable->runtime['someModel']['contain'][] = 'Box'

To be able to specify more than just the model though, you would have to set up to handle like the following (perhaps build a method accordingly):

$this->Behaviors->Containable->runtime['someModel']['contain'][] = $model_contain_array

$model_contain_array is just an arbitrary name I just chose for an array which holds the contain information you would like to add for a particular model. An example of $model_contain_array might be:

array('modelName' => array(
    'fields' => array('id', 'other'),
    'otherModelName' => array(
        'fields' => array('id', 'otherfield', 'etc')
    )
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top