Sometime we have a case of sort data with array of categories So we can't use direct 'orderBy' in drupal 8 query. We have to use 'addExpression' in query. Here we have an example for better clear this article.
Example:
In a way of query:
$products = db_query("select gfd.entity_id from node__field_category as gfd inner join node_field_data as nfd on nfd.nid=gfd.entity_id ORDER BY FIELD(gfd.field_category_target_id, 675, 676, 677), nfd.title ASC");
OR
Other way of Query:
$products = \Drupal::database()->select('node__field_category', 'gfd');
$products->join('node_field_data', 'nfd', 'nfd.nid=gfd.entity_id');
$products->fields('gfd', array('entity_id'));
$products->addExpression('FIELD(gfd.field_category_target_id, 675, 676, 677)', 'order_field');
$products->orderBy('order_field', 'ASC');
$product_ids = $products->execute()->fetchAll();
Description: Here we are using '$products->addExpression' for add special type of sorting so we will pass the field alias and field name then category id which you want for sort data and then 'order_field' is some kind of alias and we will pass in this way for ASC or DESC:
$products->orderBy('order_field', 'ASC');
So this is the simple way to sort data by array ASC/DESC in Drupal 8 query.
Note: How to sort data by array of category ids in drupal 8?
Example:
In a way of query:
$products = db_query("select gfd.entity_id from node__field_category as gfd inner join node_field_data as nfd on nfd.nid=gfd.entity_id ORDER BY FIELD(gfd.field_category_target_id, 675, 676, 677), nfd.title ASC");
OR
Other way of Query:
$products = \Drupal::database()->select('node__field_category', 'gfd');
$products->join('node_field_data', 'nfd', 'nfd.nid=gfd.entity_id');
$products->fields('gfd', array('entity_id'));
$products->addExpression('FIELD(gfd.field_category_target_id, 675, 676, 677)', 'order_field');
$products->orderBy('order_field', 'ASC');
$product_ids = $products->execute()->fetchAll();
Description: Here we are using '$products->addExpression' for add special type of sorting so we will pass the field alias and field name then category id which you want for sort data and then 'order_field' is some kind of alias and we will pass in this way for ASC or DESC:
$products->orderBy('order_field', 'ASC');
So this is the simple way to sort data by array ASC/DESC in Drupal 8 query.
Note: How to sort data by array of category ids in drupal 8?