ページごとに x 個のスレッドを出力する (それぞれに無制限の返信がある) スレッド化されたコメント システム用の創造的なデータベース構造 + フェッチ アルゴリズムを提案できる人はいますか?
クエリを実行してスレッドを取得し、ループの各インスタンスで別のクエリを実行して応答をエコーアウトできます....しかし、それは悪い考えです。
ページごとに x 個のスレッドを出力する (それぞれに無制限の返信がある) スレッド化されたコメント システム用の創造的なデータベース構造 + フェッチ アルゴリズムを提案できる人はいますか?
クエリを実行してスレッドを取得し、ループの各インスタンスで別のクエリを実行して応答をエコーアウトできます....しかし、それは悪い考えです。
2 つのレベルだけが必要な場合は、1 つのクエリを使用する方法を次に示します。
あなたのテーブル-id, parent_id, comment
列
コード
$rows = mysql_query('
select *
FROM
comments
ORDER BY
id DESC');
$threads = array();
foreach($rows as $row) {
if($row['parent_id'] === '0') {
$threads[$row['id']] = array(
'comment' => $row['comment'],
'replies' => array()
);
} else {
$threads[$row['parent_id']]['replies'][] = $row['comment'];
}
}
に$threads
は、すべてのメイン スレッドがあり、$threads[$id]['replies']
すべての返信が保持されます。スレッドはソートされています - 最新 = 最初に、いくつかのページングを追加すると、準備完了です。
コメント テーブルに、parentCommentId と rootCommentId の 2 つの列を追加します。
parentCommentId は親コメントの ID で、rootCommentId はこのスレッドを開始したコメントの ID です。
N 個のスレッドを表示するには、次の 2 つのクエリが必要です。
(これら 2 つを 1 つの GroupBy クエリに組み合わせることができます。)
これは私が今使っているものに似ています。唯一注意が必要なのは、誰かがコメントに返信したときに挿入する次の返信パスを計算することです。
サンプルデータ
ID | Comment | Path
---+------------------------------+----------
0 | Comment #1 | 01
1 | Comment #1 reply | 01_01
2 | Comment #1 reply reply | 01_01_01
3 | Comment #1 reply reply | 01_01_02
4 | Comment #2 | 02
5 | Comment #3 | 03
6 | Comment #3 reply | 03_01
SQLの例
SELECT * FROM comments ORDER BY path
PHPの例
while ($result = mysql_fetch_assoc($query)) {
$nesting_depth = count(explode("_", $result['path']));
$branch = str_repeat("--", $nesting_depth);
echo $branch {$result['comment']}";
}
結果の例
Comment #1
-- Comment #1 reply
---- Comment #1 reply reply
---- Comment #1 reply reply
Comment #2
Comment #3
-- Comment #3 reply
01_01に返信するには
SELECT path FROM comments WHERE path LIKE '01\_01\___'
$last_path = $row[0];
$last_path_suffix = substr($last_path,strrpos($last_path,'_')+1);
$next_path_suffix = str_pad($last_path_suffix+1,2,'0',STR_PAD_LEFT);
$next_path = substr($last_path,0,strlen($last_path)-strlen($last_path_suffix)).$next_path_suffix;