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

  • Did you ever find a solution? Currently facing the same issue. – Nate Jan 3 '18 at 10:02
  • 1
    I went with the solution posted on my edit. Tagging the query then using my module to customize it. Thats the best approach. If you cant figure it out, I can post an example – 113408 Jan 3 '18 at 10:06

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.