8 – Add Expression for Entity Query

I’ve been working with the entityQuery to query the db and get an array of filtered nids however I need to add an expression to my query.

I’ve checked the Query class and found a protected sqlQuery attribute that has access to addExpression(). In my case I’m not extending the class but rather instantiating it through Drupal::entityQuery('node').

Also after checking a bit I found that the Select class has a function addExpression() that does exactly what I need, but then I lose the entityQuery and has to addJoin/addField and so on for each of the fields I would like to include in my conditions.

My objective:

$expression = "
        * acos(
            cos( radians({$latitude}) )
            * cos( radians( {$latitudeField} ) )
            * cos(
                radians( {$longitudeField} )
                - radians({$longitude})
            + sin( radians({$latitude}) )
            * sin( radians( {$latitudeField} ) )
$query = Drupal::entityQuery('node')
->condition('status', 1)
->addExpression($expression, 'distance');

$nids = $query->execute();

Did I miss something ? Is there any other way to achieve what I want ?

EDIT: I found this approach but doesn’t seem straight forward

EDIT2: Better approach is this