列出用户名cakePhp的图片评论

时间:2012-07-11 11:03:37

标签: cakephp

我的评论有问题。  我有用户模型:

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. 

如何在检索有关照片的数据时与用户联系以获取与评论相关的用户名?

1 个答案:

答案 0 :(得分:4)

在调用find()之前,需要调用$this->recursive = 2,这将获取查询返回的每个对象的所有关联。或者,您可以在任何模型中设置$recursive变量。

不同类型的递归如下:

  • -1 Cake仅提取照片数据,无连接。
  • 0 Cake抓取照片数据及其域名
  • 1 Cake获取Photo,其域及其相关注释
  • 2 Cake获取一张Photo,它的域名,相关的评论和 评论'关联用户

我还建议考虑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
)));