I want to get a list that the items with a specific term in the top (like promote). The query would be like:

$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'news')
  ->sort('field_product_category', $tid, '<>') //Error <>
  ->range(0, 5);

Can I put calculation in sort condition? I do not want to make 2 queries.

  • Do you only care about having the items with a specific term at the top and then you don't care about the sorting of the rest? Because if that's the case I would just load all the nodes into an array and sort the array by that key after the fact. – Matt Sep 7 '17 at 14:32

I don't think you can sort that way with an entity query. But with a select query, you have more flexibility.

I would try something like this:

$database = \Drupal::service('database');

$query = $database->select('node_field_data', 'nfd')
  ->fields('nfd', ['id']);

$query->condition('nfd.status', 1);
$query->condition('nfd.type', 'news');
$query->range(0, 5);

$query->leftJoin('field_product_category', 'pc', 'pc.entity_id = nfd.nid');
$query->addExpression('pc.field_product_category_target_id <> :target_tid', 'is_featured', [':target_tid', $target_tid]);


$matches = $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.