Martin Cup
Martin Cup

Reputation: 2582

Cakephp recursive find including top model again

I have this cakephp find query:

$results = $this->Instrument->find('all', array('recursive' => 2, 'conditions' => array('OR' => array('Instrument.name' => $tag_search, 'Instrument.nameEN' => $tag_search))));

The Model Instrument has and belongs to many Instrumentbox. I want to find an Instrumentbox with all it's instruments searching for one instrument name with $tag_search. It returns the Insrtumentboxes that have that instrument properly but it does not include all the instruments agaion in Instrument. Is there a way to tell cakephp to load the "top model" again so that I get the structure

$results = array(
   0 => [
     'Instrument' => [
        'name' => "$tag_search value",
        '...' => ...,
        'Instrumentbox' => [
           0 => [
             '...' => '...', //everything else is properly included
             'Instrument' => [...] //this is NOT included, how can I include it?
           ]
        ]
     ]
   ]

The same thing happens when I search it with tags, so imagine in the structure above 'Tag' instead of 'Instrument', then the instruments are included in the Instrumentbox but the tags are not. So the "top model" is not included again in the structure. Do I have to make that by hand or can I make cakephp do it? Thanks in advance!

Upvotes: 1

Views: 1607

Answers (1)

Will
Will

Reputation: 4744

You Could try to do this with Contain. Its much better than using recursive over 1 anyway. You can control exactly the results you want to get, which is good for this sort of thing, and generally better for performance.

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

So, untested code:

//model
public $actsAs = array('Containable');
// controller
$this->Instrument->recursive=1;
$this->contain(array('Instrument'=> array('InstrumentBox'=> array('Instrument'))));

Upvotes: 2

Related Questions