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.

有帮助吗?

解决方案

Quoting the manual:

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

其他提示

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')
            )
        )
    )));

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top