문제

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