0

我有一个用 PHP 编写的评论脚本运行良好。它将评论保存在 mysql 评论表中,其中包含 commentid、subjectid、userid 和 timecreated 字段。我现在想实现一个回复功能。我是否应该使用用户 ID、创建时间、回复和评论字段创建一个新的回复表。

或者最好将评论表中的回复作为评论包含在内,但有两个额外的字段,一个表示此特定评论是回复,另一个表示它是回复的评论。

倾向于第一个选项,但这意味着额外的查询。

希望有经验的人给点建议!

4

2 回答 2

8

我会为referenceid和增加两列parentid。这样,您可以拥有嵌套评论,如果您愿意的话。比在查询中加入多个表更容易、更高效。如果评论不是回复,referenceid则为 0(或 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 回答