私はポストテーブルを持っています
+----+-------+--------------+
| 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 つのコメントで結果を取得します。しかし、私はこれを次のようなWebページに表示したい:
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"
}
}