Question

I have four models (Location->StatisticCategory->StatisticItem->Statistic) that I'm trying to return in a single query. The results are as expected until the query starts at the level of Location. At that point the data return contains everything down to the 3rd association in StatisticItem, but every single Statistic is null. Any idea why 4th level associations (at least here) are not returning any data?

Below is the code I'm using in my StatisticsController with Containable behavior turned on in AppModel:

$stats = $this->Location->find('all', array(
        'fields' => array(
            'Location.id',
            'Location.location'
        ),
        'conditions' => array(),
        'recursive' => 2,
        'contain' => array(
            'StatisticCategory' => array(
                'fields' => array(
                    'StatisticCategory.id',
                    'StatisticCategory.location_id',
                    'StatisticCategory.category'
                ),
                'StatisticItem' => array(
                    'fields' => array(
                        'StatisticItem.id',
                        'StatisticItem.statistic_category_id',
                        'StatisticItem.item'
                    ),
                    'Statistic' => array(
                        'fields' => array(
                            'Statistic.id',
                            'Statistic.statistic_item_id',
                            'Statistic.date',
                            'Statistic.number'
                        ),
                        'conditions' => array(
                            'Statistic.date' => $date
                        )
                    ),
                    'order' => array('StatisticItem.item')
                ),
                'order' => array('StatisticCategory.category')
            )
        ),
        'order' => array('Location.location')
    ));
Was it helpful?

Solution

The documentation for containable describes how to contain deeper associations. The following should be about what you're looking for:

$this->Location->find('all', array(
    'contain' => array(
        'StatisticCategory' => array(
            'StatisticItem' => array(
                'Statistic'
            )
        )
    )
));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top