1

ページごとに x 個のスレッドを出力する (それぞれに無制限の返信がある) スレッド化されたコメント システム用の創造的なデータベース構造 + フェッチ アルゴリズムを提案できる人はいますか?

クエリを実行してスレッドを取得し、ループの各インスタンスで別のクエリを実行して応答をエコーアウトできます....しかし、それは悪い考えです。

4

4 に答える 4

3

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']すべての返信が保持されます。スレッドはソートされています - 最新 = 最初に、いくつかのページングを追加すると、準備完了です。

于 2009-09-20T21:07:13.140 に答える
1

コメント テーブルに、parentCommentId と rootCommentId の 2 つの列を追加します。

parentCommentId は親コメントの ID で、rootCommentId はこのスレッドを開始したコメントの ID です。

N 個のスレッドを表示するには、次の 2 つのクエリが必要です。

  1. rootCommentId = id であるコメント テーブルから N 行を取得します。
  2. これらの N スレッドのすべてのコメントを取得する

(これら 2 つを 1 つの GroupBy クエリに組み合わせることができます。)

于 2009-09-18T07:46:29.657 に答える
0

これは私が今使っているものに似ています。唯一注意が必要なのは、誰かがコメントに返信したときに挿入する次の返信パスを計算することです。

サンプルデータ

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;
于 2012-10-21T17:30:11.267 に答える