0

PHPで書かれたコメントスクリプトがかなりうまく機能しています。コメントは、commentid、subjectid、userid、timecreatedのフィールドを含むmysqlコメントテーブルに保存されます。返信機能を実装したいと思います。ユーザーID、作成時間、返信、コメントIDフィールドを使用して返信の新しいテーブルを作成する必要があります。

または、コメントテーブルにコメントとして返信を含めることをお勧めしますが、2つの追加フィールドがあり、1つはこの特定のコメントが返信であることを示し、もう1つは返信であることを示します。

最初のオプションに傾いていますが、それは余分なクエリを意味します。

経験者からの提案をいただければ幸いです!

4

2 に答える 2

8

referenceid、およびの 2 つの列を追加しますparentid。そうすれば、必要に応じてコメントをネストできます。クエリで複数のテーブルを結合するよりもはるかに簡単で効率的です。コメントが返信でない場合は、referenceid0 (または null) です。返信かどうかを示す別の列を作成する必要はありません。

于 2012-05-02T02:00:01.753 に答える
5

これは元の質問に対する回答ではありませんが、これが私のプロジェクトである場合に使用する、コメントをネストするための迅速で汚いアプローチを示したかったのです。ほぼ間違いなく、よりエレガントな方法があり、ここの別のメンバーが提案を持っている可能性があります。

<?php

// Retrieve ALL comments related to this subject (including all replies and nested comments)
$rs = mysql_query( 'SELECT * FROM `comments` WHERE subjectid = '7' ORDER BY timecreated ASC' );

// Process ALL comments and place them into an array based on their parent id
// Thus we end up with something like:
// $data[ 0 ][ 0 ] = array( 'commentid' => 1, 'subjectid' => 7, 'userid' => 1, 'timecreated' => '2012-05-01 12:00:00', 'parentid' => 0 );
// $data[ 0 ][ 1 ] = array( 'commentid' => 2, 'subjectid' => 7, 'userid' => 5, 'timecreated' => '2012-05-01 14:00:00', 'parentid' => 0 );
// $data[ 2 ][ 0 ] = array( 'commentid' => 3, 'subjectid' => 7, 'userid' => 1, 'timecreated' => '2012-05-01 16:00:00', 'parentid' => 2 ); This is a reply to commentid #2
// $data[ 2 ][ 1 ] = array( 'commentid' => 4, 'subjectid' => 7, 'userid' => 5, 'timecreated' => '2012-05-01 16:30:00', 'parentid' => 2 ); This is another reply to commentid #2
// $data[ 3 ][ 0 ] = array( 'commentid' => 5, 'subjectid' => 7, 'userid' => 3, 'timecreated' => '2012-05-01 17:00:00', 'parentid' => 3 ); This is a reply to the reply with commentid #3

while ( $row = mysql_fetch_assoc( $rs ) ){
    $data[ $row['parentid'] ][] = $row;
}

function output_comments( &$data_array, $parentid ){

    // Loop through all comments with matching $parentid

    foreach ( $data_array[ $parentid ] as $k=>$v ){
        // Output all comments, open .comment DIV but do not close (for nesting purposes)
        echo '<div class="comment"><strong>' . $v['username'] . ':</strong> ' . $v['message'];

        // If there are any replies to this comment, output them by recursively calling this function
        if ( count( $data_array[ $v['commentid'] ] > 0 ){
            output_comments( $data_array, $v['commentid'] );
        }

        // Close the open DIV
        echo '</div>';
    }
}


// Call the output_comments() function, which will recursively run to support unlimited nesting

output_comments( $data, 0 );

次に、親 DIV.comment を持つ DIV.comment をインデントするだけで、ネストされたコメントのスタイルを簡単に設定できます。

<style type="text/css">
.comment .comment {
    padding-left: 30px;
}
</style>
于 2012-05-02T14:40:29.327 に答える