我是CakePHP和整个MVC架构的新手。
我想建立一个类似Reddit的评论系统,其中一条评论hasMany
评论,但也有一条评论belongsTo
(仅)一条评论。
这是通常的评论部分,其中一条评论可以回复该评论,并且回复可以有自己的答复等:
Nice article!
|
-- I didn't like it!
|
-- Well, you should have!
|
-- Yeah me neither!
现在我只设置了'hasMany'这样的关系:
class Comment extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'comment_id',
'dependent' => FALSE
)
);
}
comment_id
将包含父注释的id(如果注释没有父项,则为NULL)。
当我要求cakePHP返回属于特定帖子的所有评论时,它会返回给我(我手动添加了评论):
Array
(
[0] => Array
(
[Comment] => Array
(
[id] => 2
[post_id] => 4
[comment_id] => 4
[body] => Child of 4
[created] => 2015-01-31 18:01:27
[modified] => 2015-01-31 18:01:27
[0] => Array
(
[id] => 3
[post_id] => 4
[comment_id] => 2
[body] => Child of 2
[created] => 2015-01-01 00:00:00
[modified] => 2015-01-16 00:00:00
)
[1] => Array
(
[id] => 5
[post_id] => 4
[comment_id] => 2
[body] => 2nd child of 2
[created] => 2015-01-14 00:00:00
[modified] => 2015-01-28 00:00:00
)
)
)
[1] => Array
(
[Comment] => Array
(
[id] => 3
[post_id] => 4
[comment_id] => 2
[body] => Child of 2
[created] => 2015-01-01 00:00:00
[modified] => 2015-01-16 00:00:00
)
)
[2] => Array
(
[Comment] => Array
(
[id] => 4
[post_id] => 4
[comment_id] =>
[body] => This is the parent of all
[created] => 2015-01-21 00:00:00
[modified] => 2015-01-30 00:00:00
[0] => Array
(
[id] => 2
[post_id] => 4
[comment_id] => 4
[body] => Child of 4
[created] => 2015-01-31 18:01:27
[modified] => 2015-01-31 18:01:27
)
)
)
[3] => Array
(
[Comment] => Array
(
[id] => 5
[post_id] => 4
[comment_id] => 2
[body] => 2nd child of 2
[created] => 2015-01-14 00:00:00
[modified] => 2015-01-28 00:00:00
)
)
)
根据我的理解,它会获取所有评论,然后为每个评论重新搜索数据库以查找具有“子项”的评论。
正确的方法是什么,以使cakePHP返回一个“就绪”数组的注释,如下所示:
Array
(
[0] => Array
(
[Comment] => Array
(
[id] => 4
[post_id] => 4
[comment_id] =>
[body] => This is the parent of all
[created] => 2015-01-21 00:00:00
[modified] => 2015-01-30 00:00:00
[0] => Array
(
[id] => 2
[post_id] => 4
[comment_id] => 4
[body] => Child of 4
[created] => 2015-01-31 18:01:27
[modified] => 2015-01-31 18:01:27
[0] => Array
(
[id] => 5
[post_id] => 4
[comment_id] => 2
[body] => 2nd child of 2
[created] => 2015-01-14 00:00:00
[modified] => 2015-01-28 00:00:00
)
[1] => Array
(
[id] => 5
[post_id] => 4
[comment_id] => 2
[body] => 2nd child of 2
[created] => 2015-01-14 00:00:00
[modified] => 2015-01-28 00:00:00
)
)
)
)
)
答案 0 :(得分:1)
您可能想要使用find(' threads')。您还可以查看树行为。