1 comment.entity.inc protected CommentStorageController::updateNodeStatistics($nid)

Updates the comment statistics for a given node.

The {node_comment_statistics} table has the following fields:

  • last_comment_timestamp: The timestamp of the last comment for this node, or the node created timestamp if no comments exist for the node.
  • last_comment_name: The name of the anonymous poster for the last comment.
  • last_comment_uid: The user ID of the poster for the last comment for this node, or the node author's user ID if no comments exist for the node.
  • comment_count: The total number of approved/published comments on this node.

Parameters

$nid: The node ID.

File

core/modules/comment/comment.entity.inc, line 401
Entity controller and class for comments.

Class

CommentStorageController
Defines the controller class for comments.

Code

protected function updateNodeStatistics($nid) {
  // Allow bulk updates and inserts to temporarily disable the
  // maintenance of the {node_comment_statistics} table.
  if (!state_get('comment_maintain_node_statistics', TRUE)) {
    return;
  }

  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND status = :status', array(
    ':nid' => $nid,
    ':status' => COMMENT_PUBLISHED,
  ))->fetchField();

  if ($count > 0) {
    // Comments exist.
    $last_reply = db_query_range('SELECT cid, name, changed, uid FROM {comment} WHERE nid = :nid AND status = :status ORDER BY cid DESC', 0, 1, array(
      ':nid' => $nid,
      ':status' => COMMENT_PUBLISHED,
    ))->fetchObject();
    db_update('node_comment_statistics')
      ->fields(array(
        'cid' => $last_reply->cid,
        'comment_count' => $count,
        'last_comment_timestamp' => $last_reply->changed,
        'last_comment_name' => $last_reply->uid ? '' : $last_reply->name,
        'last_comment_uid' => $last_reply->uid,
      ))
      ->condition('nid', $nid)
      ->execute();
  }
  else {
    // Comments do not exist.
    $node = db_query('SELECT uid, created FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();
    db_update('node_comment_statistics')
      ->fields(array(
        'cid' => 0,
        'comment_count' => 0,
        'last_comment_timestamp' => $node->created,
        'last_comment_name' => '',
        'last_comment_uid' => $node->uid,
      ))
      ->condition('nid', $nid)
      ->execute();
  }
}