Question

When I try:

// Removed the limit to ensure that all of the group notes items can be found and collapsed
$recent_notes = $this->User->Note->find('all', array(
    'recursive' => 2,
    'order' => 'Note.created DESC',
    'conditions' => $conditions,
    'contains' => array(
        'NotesUser', 'Poster', 'Comment' => array('Poster')
    )
));

It does not limit the output whatsoever - I get every related model. However, when I don't specify recursive as 2, or if I specify it as 1, I am missing the Comment=>Poster model.

How can I get only the models I need? Thanks!

Was it helpful?

Solution

Recursive is ignored as soon as you set contain.

From the docs:

The ContainableBehavior has a number of options that can be set when the Behavior is attached to a model. The settings allow you to fine tune the behavior of Containable and work with other behaviors more easily.

recursive (boolean, optional) set to true to allow containable to automatically determine the recursiveness level needed to fetch specified models, and set the model recursiveness to this level. setting it to false disables this feature. The default value is true.

Make sure the array key is set as 'contain', not 'contains' as you've posted above, so like:

$this->Post->find('all', array('contain' => 'Tag'));

I'm also assuming that you're loading and attaching the containable behavior correctly. If you're having trouble, the documentation is here.

OTHER TIPS

To get only the models you need, use the [Containable behavior]:

  • set recursive to -1
  • use 'contain' singular, NOT 'contains' plural, like you have
  • make sure you're setting the $actsAs variable in your model: public $actsAs = array('Containable');

Everyone that I know sets $this->recursive = -1; in the AppModel... this defaults everything to recursive -1 so you don't ever have to set it again unless you want to include more data...and in those cases, I almost always use contain(), not $recursive.

If you have deep association, for example History belongsTo Warehouse and Warehouse belongsTo Company and you want only Warehouse.Company, you can also use

'contain'   => array('Warehouse.Company')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top