CakePHP Containable behaviour not working as expected
-
14-07-2021 - |
Question
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.
Solution
Quoting the manual:
When using ‘fields’ and ‘contain’ options - be careful to include all foreign keys that your query directly or indirectly requires.
OTHER TIPS
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