0

I've been searching for days but cant find a working answer for my issue.

I have a Drupal 8.6.7 site with search_api and search_api_solr installed. I have a view based on solr results. I want to sort the results by creation date in a descending order, but i want the first three items to be created by members with the role "redactie".

This is what i have so far, but it doesn't seem to affect the results in any way.

function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if($view->id() == 'search_content') {
    // get members
    $rids = \Drupal::entityQuery('user')->condition('status', 1)->condition('roles', 'redactie')->execute();
    if(count($rids) > 0) {
      // get latest 3 bundles, created by one of the members
      $nids = \Drupal::entityQuery('node')->condition('type','bundle')->condition('uid', $rids, 'IN')->sort('created' , 'DESC')->range(0,3)->execute();
      if(count($nids) > 0) {
        // add these bundle ids to the query order
        $query->addOrderBy(null, 'node_field_data.nid IN (' . implode(',', $nids) . ')', 'DESC', 'redactie_order_by');

        // sort the rest of the results by creation date
        $query->addOrderBy(null, 'node_field_data.created', 'DESC', 'created_order_by');
      }
    }
  }
}

Can anyone tell me how to fix this?

  • This hook is supposed to use ViewExecutable and QueryPluginBase as documented on hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query). So do that and at the very top of your file just in of the next lines after the opening <?php tag put use Drupal\views\Plugin\views\query\QueryPluginBase; and use Drupal\views\ViewExecutable;. Maybe consider getting a Drupal-friendly IDE like PHPStorm... – leymannx Jan 25 at 16:00
  • thanks leymannx, i've updated my function but that doesn't change the order of the results – Sander Jan 25 at 16:43
  • Solr queries don't use the database (it would defeat the purpose of using Solr if they did). You'll need to use hook_search_api_solr_query_alter and alter the query provided by the Solarium library. Keep in mind it's not a database query, so you'll probably have to consult the Solr docs to find out the correct syntax to use to reproduce the sorting you need. If you're on an older version of Solr (4.x and below), the options for complex sorting are somewhat limited, so be sure that you're consulting the right version of the documentation to avoid frustration – Clive Jan 26 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.