I have the following code to alter a view and filter IN only specific nodes

function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if($view->id() == 'myview'){
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == "node_field_data.nid") {
          $condition = array(
            'field' => "node_field_data.nid",
            'value' => [2,4,6,1,3,5],
            'operator' => 'in',
    //this does not work    
    //$query->addOrderBy('node_field_data','nid', 'ASC', '', [2,4,6,1,3,5]);    

and I want to sort them with this specific order [2,4,6,1,3,5]

I tried not putting any sorting field but the view sorts the nodes by created date. How can I tell the view to sort them in this manner ?

I think I need to use ORDER BY FIELD('node_field_data'.'nid','2','4','6','1','3','5') in sql but I don't know how its done in drupal

I have seen this answer but don't know how it applies to my case

any help would be appreciated

1 Answer 1


OK I figured it out

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,2,4,6,1,3,5)', 'ASC', 'order_field');
  • What is 'order_field' here? already node_field_data.nid has been specified in FIELD. What should I give in 'order_field'?
    – siddiq
    Commented Jul 19, 2018 at 1:45
  • @siddiq order_field is an (optional) alias - for me, it was necessary because my $field is a formula. I also found it necessary to remove all sort criteria under the View's UI for it to work.
    – vrwired
    Commented Aug 21, 2019 at 19:15
  • @GiorgosK - this everytime creates an error for me saying column name not found. Is this something that you came across ?
    – AkiShankar
    Commented Jul 21, 2020 at 14:54
  • @AkiShankar sorry have not seen anything and this code is still running where it was deployed
    – GiorgosK
    Commented Jul 22, 2020 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.