我的数据库上有3个用户表:
Users
users_twitter
users_web
用户是users_twitter
和users_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
只有一级,我需要两级。
答案 0 :(得分:0)
在AppModel中添加
public $actsAs = array('Containable');
在你的索引中:
public function index($idPost) {
return $this->Comment->find('all', array(
'contain' => array('User.UsersWeb')));
}
您的用户模型必须与UsersWeb模型相关联才能使其正常工作。
为什么还要返回控制器索引中的数据?你在使用requestAction吗?你为什么不使用分页?你真的想在一个页面上显示数百条评论吗?
请参阅http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html