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.
2 Answers
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');
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')
->fieldCondition(...)
->addTag('my_tag');
-
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.– StevenOct 21, 2013 at 17:13
-
@Steven yeah
havingCondition()
is probably better to use thanhaving()
actually, unless it needs a complex expression. The only ways to expose those methods are to write a subclass ofEntityFieldQuery
which implements them (and alters the underlying query by overridingEntityFieldQuery::execute()
), or alter the query like the code above. Fortunately it's a very small amount of code– Clive ♦Oct 21, 2013 at 17:18