我有类似博客系统的东西。每个条目都有评论。每条评论都由用户创建。
我目前正在控制器上的'view'操作中使用read函数来检索所有数据。
模型之间的关系已经创建(belongsTo,hasMany ......等)
当调用入口视图时,我会得到这样的结果:
['Entry'] => Array
(
[id] => 1
[body] => 'xxxxxx'
[...] => ...
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[body] => This is an example of a comment guys!
[created] => 0000-00-00 00:00:00
)
[1] => Array
(
[id] => 2
[user_id] => 1
[body] => This is the 2nd comment!!!
[created] => 0000-00-00 00:00:00
)
)
有没有办法,使用读取功能,还可以检索评论的“递归”数据,例如与user_id相关的用户数据? (为了得到他们的名字等)。
我期待这样的事情:
['Entry'] => Array
(
[id] => 1
[body] => xxxxxx
[...] => ...
)
[Comment] => Array
(
[0] => Array
(
[Comment] => Array
(
[id] => 1
[user_id] => 1
[body] => This is an example of a comment guys!
[created] => 0000-00-00 00:00:00
)
[User] => Array
(
[id] => 1
[username] => myusername
[created] => 0000-00-00 00:00:00
)
)
[1] => Array
(
[Comment] => Array
(
[id] => 1
[user_id] => 2
[body] => fasdfasfaT
[created] => 0000-00-00 00:00:00
)
[User] => Array
(
[id] => 2
[username] => myusername2
[created] => 0000-00-00 00:00:00
)
)
)
感谢。
答案 0 :(得分:1)
是的,是的。
您可以通过recursive
属性控制关联的深度,或者使用containable
行为来准确指定要包含的模型。我总是为AppModel.php
($actsAs = array('Containable');
)中的所有模型启用此行为。然后像这样使用它:
$this->Entry->find('all', array(
...
'contain' => array('Comment' => 'User')
));
结果如下:
['Entry'] => Array
(
[id] => 1
[body] => xxxxxx
[...] => ...
)
[Comment] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[body] => This is an example of a comment guys!
[created] => 0000-00-00 00:00:00
[User] => Array
(
[id] => 1
[username] => myusername
[created] => 0000-00-00 00:00:00
)
)
)
根据我的经验,Cake查询深层关联并不是非常有效。在您的情况下,它会为每个Comment
生成一个查询,以获取其User
。我会通过让Cake仅获取注释,然后获取注释的用户ID,在一个查询中获取具有这些ID的所有用户,然后将该用户信息添加到原始结果来避免它。