Use an EntityQueue order in a custom query

As you might know, the Entityqueue modules is an evolvement of Nodequeue.

It has a great integration with Views but if you need to apply a queue to a custom query here is an example:

Drupal 9+

// Gets a list of users with the "editor" role and orders them by the
// delta of an entityqueue with machine name "authors".
$db = \Drupal::database();
$query = $db->select('users_field_data', 'u');
$query->join('user__roles', 'ur', 'ur.entity_id=u.uid');
$query->addField('u', 'uid');
$query->condition('u.status', 1);
$query->condition('ur.roles_target_id', 'content_editor');
if ($db->schema()->tableExists('entity_subqueue__items')) {
  $query->leftJoin('entity_subqueue__items', 'eqn', 'eqn.items_target_id=u.uid');
  $or = $query->orConditionGroup();
  $or->isNull('eqn.entity_id');
  $or->condition('eqn.entity_id', 'editor');
  $query->condition($or);
  // Order null last.
  $query->addExpression('CASE WHEN eqn.items_target_id IS NULL then 1 else 0 END', 'order_eqn_null');
  $query->orderBy('order_eqn_null', 'ASC');
  $query->orderBy('eqn.delta', 'ASC');
}

$uids = $query->execute()->fetchCol();

Drupal 7

$query = db_select('node', 'n');
// Every entity type has it's own table record.
$query->leftJoin('field_data_eq_node', 'eqn', 'eqn.eq_node_target_id=n.nid');
$query->fields('n', array('nid'));
$query->condition('n.type', 'event');

// Order by priorities entityqueue.
$eqn_or = db_or();
$eqn_or->isNull('eqn.bundle');
$eqn_or->condition('eqn.bundle', 'priorities');
$query->condition($eqn_or);

// Order null last.
$query->addExpression('CASE WHEN eqn.entity_id IS NULL then 1 else 0 END', 'order_eqn_null');
$query->orderBy('order_eqn_null','ASC');
$query->orderBy('eqn.delta', 'ASC');
$selectpriorities = $query->execute()->fetchCol();

 

********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************