0

I can't figure out how to add following expression to the views query:

ORDER BY FIELD(field_dataid,3,2,1,4)

QueryPluginBase only gives the option to add:

$query->addOrderBy('node_field_data', 'nid', ASC);

But doesn't give the option to add an expression.

The Sql interface has the options to add an expression:

  $query->addExpression('FIELD(node_field_data.nid,3,2,1,4)', 'order_field');
  $query->orderBy('order_field', 'ASC');

But this doesn't work with the views query object.

So how can i add orderby expression to the views query object?

1

There is a similar answer here: https://drupal.stackexchange.com/a/200662/79998

You should either use $query->addField() to add the expression and then append or unshift in $query->orderby array, or you can use directly $query->addOrderBy() to add the expression and order, if it's ok to be added last.

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,3,2,1,4)', 'ASC', 'order_field');

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.