Skip to content

Instantly share code, notes, and snippets.

@init90
Created April 19, 2022 15:50
Show Gist options
  • Save init90/22f7cf96c311b7ec08a2ebb914075a77 to your computer and use it in GitHub Desktop.
Save init90/22f7cf96c311b7ec08a2ebb914075a77 to your computer and use it in GitHub Desktop.
Sort comments by rating and leave default sorting for threads.
/**
* Implements hook_query_TAG_alter() for comments.
*
* @see CommentStorage::loadThread().
*/
function gojara_global_query_comment_filter_alter(AlterableInterface $query) {
// Sort comments by rating and leave default sorting for threads.
if ($query->getMetaData('field_name') === 'comment') {
$order_by = &$query->getOrderBy();
$expression = &$query->getExpressions();
if (isset($order_by['torder'])) {
// Remove standard comments sorting options.
unset($order_by['torder']);
unset($expression['torder']);
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$host_entity = $query->getMetaData('entity');
/**
* Sub-query to get comments rating for main comments and also clone
* parent comment rating for thread comments(they not support rating)
* for proper sorting work.
*/
$db = \Drupal::database();
$sub_query = $db->select('comment_field_data', 'c2');
$sub_query->leftJoin('comment__field_fivestar_rating', 'rating', 'rating.entity_id = c2.cid AND rating.bundle = \'comment\'');
$sub_query->addField('rating', 'field_fivestar_rating_rating', 'comment_rating');
$sub_query->condition('c2.entity_id', $host_entity->id());
$sub_query->condition('c2.entity_type', 'comment', '=');
// Find parent comment for thread comment. For that we use specifics how
// comments threads works.
// More info here: \Drupal\comment\CommentStorage::loadThread().
$sub_query->where('SUBSTRING_INDEX(SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)), \'.\', 1) = SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) - 1))');
$query->distinct();
// Sort by comments rating.
$query->addExpression('(' . $sub_query . ')', 'comment_rating');
$query->orderBy('comment_rating', 'DESC');
// Sort by thread weights.
$query->addExpression('SUBSTRING_INDEX(SUBSTRING(thread, 1, (LENGTH(thread) - 1)), \'.\', 1)', 'thread_weight');
$query->orderBy('thread_weight', 'ASC');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment