1

Using search_api I have an query with the following condition

$query->condition('nid', [1,5,3,7,10], 'IN')

I know I can sort by things like created date or title, but what if I knew the exact order I wanted everything returned in. So in the above example where I'm grabbing the nodes with ids [1,5,3,7,10] what if I want the results returned in that order too. So after executing in the array of results the nodes appear in 1,5,3,7,10 order.

I tried using orderBy but that does not appear to be a method of the search_api query class

Call to undefined method Drupal\search_api\Query\Query::orderBy()

UPDATE:

I tried passing a sort function into sort on the query like so

      $query->sort(function($a,$b) use ($allowed_nids){
        $pos_a = array_search($a->nid, $allowed_nids);
        $pos_b = array_search($b->nid, $allowed_nids);
        if(($pos_a == $pos_b)){
          return 0;
        }
        return ($pos_a < $pos_b) ? -1 : 1;
      });

But that gave me the error

TypeError: Illegal offset type in isset or empty in Drupal\search_api\Query\Query->sort() (line 465 of modules/contrib/search_api/src/Query/Query.php).

Which I assume means that it can only take strings for the sort function and not anonymous methods.

1 Answer 1

1

The error you are receiving is due to the first argument of sort() expecting the field name, not a function: https://git.drupalcode.org/project/search_api/-/blob/8.x-1.x/src/Query/Query.php#L462

As to your issue, I don't believe you can sort them in the query itself, but you can sort the results by the array:

$nids = [1,5,3,7,10];
$query->condition('nid', $nids, 'IN')
$results = $query->execute();

$sorted_results = array_merge(array_flip($nids), $results);

Your Answer

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

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