我有一个类似博客系统的东西。每个条目都可以有注释。每个注释都由用户创建。
我目前正在控制器上的"查看"操作中使用读取功能来检索所有数据。
模型之间的关系已经创建(属于,有很多...等)
调用条目视图时,我得到如下内容:
['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
)
)
)
谢谢。
是的,是的。
可以通过 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 的所有用户,然后将该用户信息添加到原始结果中。