I am currently converting code from Drupal 7 to Drupal 8. So far I am unable to find resources on how to convert the call to orderBy() which uses an expression.

$query->orderBy("FIELD(node.nid, '5,12,3,6')", 'ASC'); 

Based on D8 Select::orderBy, it only accepts alias or fields.

What is the code I should use in Drupal 8?

  • $query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'order_field'); $query->orderBy('order_field', 'ASC'); Try this – Shreya Shetty May 2 '16 at 4:51
  • I tried that but it will not work as it adds the FIELD command to the select fields. e.g. SELECT FIELD(node.nid, 5,12,3,6') AS order_field – Spencer Chang May 2 '16 at 5:45

I did a workaround by implementing a CASE statement then sorting by the value.

    CASE node.nid
        WHEN 5 THEN 1
        WHEN 12 THEN 2
        WHEN 3 THEN 3
        WHEN 6 THEN 4
        ELSE 5
", 'order_field');

$query->orderBy("order_field", 'ASC');

Hopefully they'll add another function to handle these special statements in the future.

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.