How to add an SQL expression to the entity query? (D8) Assume we have an entity query like the following:

$query = \Drupal::service('entity_type.manager')-&gt;getStorage('taxonomy_term')-&gt;getQuery();
$tids = $query-&gt;condition('vid', 'tags')-&gt;execute();


and we need to add some SQL expression and condition based on it, like the following:

Replace(name, ' ', '-') = 'some-tag'


How to do that?

The Drupal\Core\Entity\Query\Sql\Query class does not have methods for doing so (unlike Drupal\Core\Database\Query\Select).
Using query tags and metadata the underlying Select query can be altered easily.

$query = \Drupal::service('entity_type.manager')-&gt;getStorage('taxonomy_term')-&gt;getQuery();

// Add tag and any metadata to the entity query.
$query-&gt;addTag('my_category')
  -&gt;addMetaData('my_category', $dynamic_category_name);

$tids = $query-&gt;condition('vid', 'tags')-&gt;execute();


And then in my_module.module file:

/**
 * Implements hook_query_TAG_alter() for my_category tag.
 */
function my_module_query_my_category_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $expression = "Replace(taxonomy_term_field_data.name, ' ', '-')";
  $args = [
    ':dynamic_category_name' =&gt; $query-&gt;getMetaData('my_category'),
  ];

  $query-&gt;addExpression($expression);
  $query-&gt;where($expression . ' = :dynamic_category_name', $args);
}