Reputation: 805
I have a problem with my comments. I have User model:
public $hasMany = array('Photo','Comment');
Comment model:
public $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id'
),
'Photo'=>array(
'className'=>'Photo',
'foreignKey'=>'photo_id'
)
);
and Photo Model
public $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id'
)
);
public $hasMany = array(
'Comment'=>array(
'className'=>'Comment',
'foreignKey'=>'photo_id'
)
);
When I read data of a photo I got:
'Photo' => array -> info about photo which is ok for me
'User' => array -> info about user ok for me
'Comment' => array -> all comments but only with id of users.
How can I connet comments with users to get username related with comment while retrieving data about photo?
Upvotes: 0
Views: 688
Reputation: 876
You need to call $this->recursive = 2
before you call find(), that will fetch all associations of every object returned by your query. Alternatively you can set the $recursive
variable inside any of your models.
The different types of recursion are as follows:
I also suggest considering Containable since you have complete control of all the data that is returned, down to specifying each field in any association
The photo model:
<?php
class Photo extends AppModel {
public $actsAs = array('Containable');
}
And your find method will look like this:
<?php
$this->Photo->find('all', array(
'contain' => array(
'User',
'Comment' => array(
'User' = array(
'fields' => array('username')
),
'conditions' => array(
'Comment.erased' => 0
)
))
'conditions' => array(
'Photo.id' => $id
)));
Upvotes: 4