1

我有两张表,一张是“forum_topic”,第二张是“forum_comments”

我想要一个 CodeIgniter 查询来获取 forum_topic 详细信息,例如我有一个查询“select * from forum_topic where topic_id = 1”然后我想要基于“forum_comments.topic_id = forum_topic.topic_id”的 forum_comments 表中的所有评论,但是论坛评论应该是树形视图格式,因为我们也有每条评论的 n 级回复,这些回复也存储在“forum_comments”表中,您可以在 forum_comments 表中看到一个字段“parent”,其中包含“comment_id”的回复制成。

1 - 论坛主题

CREATE TABLE IF NOT EXISTS `forum_topic` (
  `topic_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `category` int(11) NOT NULL,
  `content` text NOT NULL,
  `created_by` int(11) NOT NULL,
  `created_date` datetime NOT NULL,
  `view_count` int(11) NOT NULL,
  `last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status` enum('publish','unpublish') NOT NULL,
  PRIMARY KEY (`topic_id`)
)

2 - 论坛评论

CREATE TABLE IF NOT EXISTS `forum_comments` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `comment_by` int(11) NOT NULL,
  `topic_id` int(11) NOT NULL,
  `parent` int(11) NOT NULL DEFAULT '0',
  `comment` text NOT NULL,
  `commented_date` datetime NOT NULL,
  `commented_type` enum('user','admin') NOT NULL DEFAULT 'user',
  `status` enum('publish','unpublish','block') NOT NULL,
  PRIMARY KEY (`comment_id`)

)

4

3 回答 3

0

如果您正在寻找大量循环或连接的效率,我会说对“forum_comments”表使用“左右树”格式:

http://www.sitepoint.com/hierarchical-data-database-2/

http://en.wikipedia.org/wiki/Nested_set_model

于 2013-03-13T06:45:29.077 回答
0

您可以将这样的模型函数与查询一起使用

function getComments($topic_id){
    $query  =   "   SELECT
                        fc.*
                    FROM forum_topic AS ft
                    INNER JOIN forum_comments AS fc ON ft.topic_id  =   fc.topic_id
                    WHERE ft.topic_id   =   $topic_id
                    ORDER BY fc.parent";
    return $this->db->query($query)->result();
}
于 2013-03-13T06:55:29.773 回答
0

你可以试试这个查询,看看它是否有效:

Select top.*,com.* from forum_topic as top left join forum_comments as com on com.topic_id = top.topic_id where top.topic_id = 1 order by top.topic_id desc
于 2013-03-13T06:57:32.020 回答