Is there any way I can use having clause with EntityFieldQuery? I want to get the nodes which have same field value similar to HAVING clause in SQL. Or do I need to do other ways? Please suggest if there is any good way to do this.


You can use the havingCondition available in the query builder.

$query = db_select('node, 'n');

// add fields or other conditions

$query->havingCondition('nid', array(1, 2, 3), 'IN');
  • EntityFieldQuery doesn't have that method... – Clive Oct 21 '13 at 17:04
  • Thank you Mike and Clive. I did it using havingCondition for now. – cissharp Oct 21 '13 at 18:48

You could subclass EntityFieldQuery and add a having() method, or (probably quicker) you can add a tag to the query, and use hook_query_TAG_alter() to alter it when it's a standard SelectQuery:

function MYMODULE_query_my_tag_alter(QueryAlterableInterface $query) {
  $query->having('some_field > :val', array(':val' => $some_val));

To use that with your query:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  • There is a havingCondition you could take a look at api.drupal.org/api/drupal/includes%21database%21select.inc/… though you would probably still need to do something to expose it. – Steven Oct 21 '13 at 17:13
  • @Steven yeah havingCondition() is probably better to use than having() actually, unless it needs a complex expression. The only ways to expose those methods are to write a subclass of EntityFieldQuery which implements them (and alters the underlying query by overriding EntityFieldQuery::execute()), or alter the query like the code above. Fortunately it's a very small amount of code – Clive Oct 21 '13 at 17:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.