1

我的数据库上有 3 个用户表:

  • Users
  • users_twitter
  • users_web

Users 是 和 的父users_twitterusers_web

然后是另一个评论表。两种用户都可以发表评论。

因此,当我想显示评论时,我需要获取每条评论的作者信息。为了做到这一点,我正在使用这样的$belongsTo变量/Model/Comment.php

public $belongsTo = array(
    'users' => array(
        'foreignKey' => 'idUser'
    )
);

在 Controller/CommentController 中,当我这样做时:

public function index($idPost) {
    $this->Comment->recursive = 0;
    return $this->Comment->find('all');
}

我得到这种数组:

[0] => Array
        (
            [Comment] => Array
                (
                    [id] => 1
                    [idPost] => 441
                    [idUser] => 387371023
                    [comment] => hello word
                    [created] => 2012-03-01 00:00:00
                )

            [User] => Array
                (
                    [id] => 1
                    [username] => myname
                )
        )

我想要的是获得更多信息,用户的子类型之一,这取决于子类型表上 ID 的存在。

如果它是 user_web 表的 id,我想得到这个:

[0] => Array
        (
            [Comment] => Array
                (
                    [id] => 1
                    [idPost] => 441
                    [idUser] => 387371023
                    [comment] => hello word
                    [created] => 2012-03-01 00:00:00
                )

            [User] => Array
                (
                    [id] => 1
                    [username] => myname
                    [users_web] =>  Array
                        (
                            [id] => 1
                            [username] => myName
                            [password] => XXXXX
                            [verified] => 1
                            [created] => 1
                        )
        )

您知道 CakePHP 是否可以做到这一点?据我所知,$hasOne我只多升一级,我需要两级。

4

1 回答 1

0

在您的 AppModel 中添加

public $actsAs = array('Containable');

在您的索引中:

public function index($idPost) {
    return $this->Comment->find('all', array(
        'contain' => array('User.UsersWeb')));
}

您的 User 模型必须与 UsersWeb 模型相关联才能完成这项工作。

有关完整说明,请参阅http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html# contains-deeper-associations 。

另外为什么要返回控制器索引中的数据?您为此使用 requestAction 吗?为什么不使用分页?您真的想在一页上显示数百条评论吗?

http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html

于 2012-03-25T18:07:41.867 回答