【问题标题】:hasOne subtype on CakePHPCakePHP 上的 hasOne 子类型
【发布时间】:2012-03-25 17:59:23
【问题描述】:

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

  • Users
  • users_twitter
  • users_web

Users 是 users_twitterusers_web 的父级。

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

所以,当我想展示 cmets 时,我需要获取每条评论的作者信息。 为此,我在/Model/Comment.php 上使用变量$belongsTo,如下所示:

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 我只多升一级,我需要两级。

【问题讨论】:

    标签: cakephp cakephp-2.0 has-one subtype


    【解决方案1】:

    在你的 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#containing-deeper-associations

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

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

    【讨论】:

    • 谢谢它的工作!关于我为什么要退货,这只是为了举例。我通常使用 $this->set ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多