我的评论有问题。 我有用户模型:
public $hasMany = array('Photo','Comment');
评论模型:
public $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id'
),
'Photo'=>array(
'className'=>'Photo',
'foreignKey'=>'photo_id'
)
);
和照片模型
public $belongsTo = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id'
)
);
public $hasMany = array(
'Comment'=>array(
'className'=>'Comment',
'foreignKey'=>'photo_id'
)
);
当我读到我得到的照片数据时:
'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.
如何在检索有关照片的数据时与用户联系以获取与评论相关的用户名?
答案 0 :(得分:4)
在调用find()之前,需要调用$this->recursive = 2
,这将获取查询返回的每个对象的所有关联。或者,您可以在任何模型中设置$recursive
变量。
不同类型的递归如下:
我还建议考虑Containable,因为您可以完全控制所有返回的数据,直到指定任何关联中的每个字段
照片模型:
<?php
class Photo extends AppModel {
public $actsAs = array('Containable');
}
你的find方法看起来像这样:
<?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
)));