1

我有张贴表 +----+-------+--------------+ | Id | Name | Message | +====+=======+==============+ | 1 | John | John's msg | | 2 | Marco | Marco's msg | | 3 | Ivan | Ivan's msg | +----+-------+--------------+

评论表,PostId 为外键

+----+-------+--------------+--------+
| Id | Name  | Comment      | PostId |
+====+=======+==============+========+
| 1  | John  | John's msg   | 2      |
| 2  |Joseph |Joseph's msg  | 2      |
| 3  | Ivan  | Ivan's msg   | 2      |
| 4  |Natalie|Natalie's msg | 1      |
+----+-------+--------------+--------+

创建闭包表以保持评论层次结构,如下所述:http: //karwin.blogspot.ba/2010/03/rendering-trees-with-closure-tables.html

封闭表 +----------+-------------+ | ancestor | descendant | +==========+=============+ | 1 | 1 | | 1 | 2 | | 1 | 3 | | 4 | 4 | +----------+-------------+

为了在 PHP 中创建祖先>后代关系,我使用了这个查询

`select c.* from comments c join closure t on (c.id = t.descendant ) where c.postid=2`

我从评论表中获得了第 3 条评论的结果。但我想在这样的网页上显示这个:

Post Id=2
    Comment id=1
        Comment id=2
        Comment id=3

我不知道如何告诉 PHP 谁是祖先,谁是后代。这是我最好的尝试:

$sql = "select c.* from comments c join closure t on 
(c.id = t.descendant ) where c.postId=2";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"]."". "Message:" . $row["comment"].";
       }
} else {
    echo "No comments yet";
}

但它只显示所有评论。需要一种方法来识别评论何时是后代。

while($row = $result->fetch_assoc()) {
if (ascendant){
    echo "ascendant comment"
}
else{
    echo "tab"."descendant comment"
}
}
4

0 回答 0