日期:2014-05-18  浏览次数:20641 次

有谁看过尚学堂的BBS 2007的教程吗?请教。。。
说是在,真的还是没看懂这个BBS的思路,请教大家了。

先是数据库设计
SQL code
create table bbs
(
id int primary key auto_increment,
pid int,
rootid int,
title varchar(255),
cont text,
pdate datetime,
isleaf int
);

insert into bbs values (null, 0, 1, '蚂蚁大战大象', '蚂蚁大战大象', now(), 1);
insert into bbs values (null, 1, 1, '大象被打趴下了', '大象被打趴下了',now(), 1);
insert into bbs values (null, 2, 1, '蚂蚁也不好过','蚂蚁也不好过', now(), 0);
insert into bbs values (null, 2, 1, '瞎说', '瞎说', now(), 1);
insert into bbs values (null, 4, 1, '没有瞎说', '没有瞎说', now(), 0);
insert into bbs values (null, 1, 1, '怎么可能', '怎么可能', now(), 1);
insert into bbs values (null, 6, 1, '怎么没有可能', '怎么没有可能', now(), 0);
insert into bbs values (null, 6, 1, '可能性是很大的', '可能性是很大的', now(), 0);
insert into bbs values (null, 2, 1, '大象进医院了', '大象进医院了', now(), 1);
insert into bbs values (null, 9, 1, '护士是蚂蚁', '护士是蚂蚁', now(), 0);



核心逻辑是
Java code
<%
    ArrayList<Article> articlesList = new ArrayList<Article>();
    Connection conn = DB.getConn();
    tree(articlesList, conn, 0, 0);
    DB.close(conn);
%>


tree方法
Java code
try {
            while (rs.next()) {
                Article article = new Article();
                article.setId(rs.getInt("id"));
                article.setPid(rs.getInt("pid"));
                article.setRootId(rs.getInt("rootid"));
                article.setTitle(rs.getString("title"));
                article.setPdate(rs.getTimestamp("pdate"));
                article.setLeaf(rs.getInt("isleaf") == 0 ? true : false);
                articlesList.add(article);
                if (!article.isLeaf()) {
                    tree(articlesList, conn, article.getId(), grade + 1);
                }
            }


调用tree方法,初始数据是pid为0作为第一个帖子的父ID?第二个0是缩进的。
在递归的时候,为什么总是把当前的帖子ID作为父亲的pid进行查询啊?


------解决方案--------------------
在递归的时候,为什么总是把当前的帖子ID作为父亲的pid进行查询啊?

这个是递归调用

当前id 作为 父id 传进去是 看看 当前id 下面 是否存在 他的孩子

打比方说

当前id=5;
。。。。
tree( , , 5, )

就是用递归调用 把 所有5下面的孩子(所有pid=5的)查找出来;
如果pid为5的 有3个 a, b, c, 当检索到a 时候 又深入进去查找 以a 的id作为父id的 其他项(此时还没有去检索b ,c)
如果a 下面有孩子 g,h,s。就进入检索a下面的孩子 检索 g 时候 再次判断 g 是否有孩子(h,s )还没有检索,就这样一层一层的深入下去 。直到有一个孩子是叶子 (就是他已经是本次检索的最后一个了 他后面没有孩子了) ,,就开始一层一层返回了

返回到g ,然后开始检索 和g 共一个父亲的h ,,一直检索下去 ,返回 后 再 检索 s 这样 一层一层 检索 然后一层一层 返回 。就是这个效果。
------解决方案--------------------
这个数据库详细解释下: id 就不用说了吧。 pid:就是说当前帖子的父节点,也就是说这个帖子回富了的那个帖子的id号。 rootid:就是说这个话题的根节点是哪个,我们知道一个帖子实际上就是一个树状结构,有一个根节点,这个rootid就是说的这个根节点的id号。title cont pdate这些都显而易见,isleaf就是说当前的帖子是不是一个叶子节点,在这个数据库中,0代表是叶子节点,可以理解为他的下面没有了回复的帖子,1则代表有回复帖子,为非叶子节点。