gpt4 book ai didi

mysql - 将评论与自己联系起来

转载 作者:行者123 更新时间:2023-11-29 12:26:15 25 4
gpt4 key购买 nike

我是 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
)

)
)
)
)

最佳答案

您可能想使用 find('threaded')。您还可以查看树的行为。

关于mysql - 将评论与自己联系起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com