I get node list in my Conroller:

$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->sort('created' , 'DESC');
$nids = $query->execute();

How can add sorting by Flag counter?


The flag count in another table called flag_counts so you should do join with node table try the following:

$database = \Drupal::database();
$query = $database->select('node', 'n');
$query->fields('n', [])
  ->condition('nfd.status', '1', '=');
// Inner join to get the node status.
$query->innerJoin('node_field_data', 'nfd', 'nfd.nid = n.nid');
// This join to get the flag counts by node.
$query->leftJoin('flag_counts', 'fc', 'n.nid = fc.entity_id');
$query->fields('fc', ['entity_id', 'count']);
// Sort by count.
$query->orderBy('fc.count', 'DESC');
$query->range(0, 10);
$result = $query->execute()->fetchAll();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.