Use an EntityQueue order in a custom query

Last updated on 22/06/2016

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:

$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->condition('eqn.bundle', 'priorities');
// Order null last.
$query->addExpression('CASE WHEN eqn.entity_id IS NULL then 1 else 0 END', 'order_eqn_null');
$query->orderBy('', 'ASC');
$selectpriorities = $query->execute()->fetchCol();