0

I'm trying to retrieve specific fields from a model that is 2 levels deep. Im using the container behaviour but the bottom level is not being retrieved properly.

Heres the code:

$this->Review->Behaviors->attach('Containable');
    $latestReviews = $this->Review->find('all', array(
        'contain' => array(
            'Business' => array(
                'fields' => array('Business.name'),
                'BusinessType' => array(
                    'fields' => array('BusinessType.url')
                )
            ),
        ),
        'fields' => array('overall'),
    ));

And the Array it is returning:

array(
(int) 0 => array(
    'Review' => array(
        'overall' => '2'
    ),
    'Business' => array(
        'name' => 'Business Name',
        'business_type_id' => '1',
        'id' => '2012'
    )
))

However rather than give me the business type id I want it to return me the BusinessType url field.

Can anyone see where Im going wrong? Im sure this is inline with the CakePHP documentation.

cowls
  • 24,013
  • 8
  • 48
  • 78
  • I think your `BusinessType` is incorrectly nested - bring it up one level. `contain('Business' => array(...), 'BusinessType' => array(...))` – Ross Oct 24 '12 at 19:36

3 Answers3

6

Quoting the manual:

When using ‘fields’ and ‘contain’ options - be careful to include all foreign keys that your query directly or indirectly requires.

ADmad
  • 8,102
  • 16
  • 18
0

I think you should remove the 'fields' option and the model name in the fields lists:

$this->Review->Behaviors->attach('Containable');
$latestReviews = $this->Review->find('all', array(
    'contain' => array(
        'Business' => array(
            'fields'       => array('name'),
            'BusinessType' => array(
                'fields' => array('url')
            )
        )
    )));
nIcO
  • 5,001
  • 24
  • 36
0

Using the 3.x version :

If you have limited the fields you are loading with select() but also want to load fields off of contained associations, you can pass the association object to select():

// Select id & title from articles, but all fields off of Users.
$query = $articles->find()
    ->select(['id', 'title'])
    ->select($articles->Users)
    ->contain(['Users']);

The $articles is the equivalent for $this->Review in the question

TheFuquan
  • 1,737
  • 16
  • 18