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->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();