9

How can I retrieve the 'count(*)' from a query in drupal 7? The query needs to include a custom content type and a custom field.

Notes

  • Custom Content Type: employees

  • Custom Field Name: field_employees_email

  • As a note, I'm looking to add

    WHERE field_employees_email = '[email protected]'

to the query...

So far, I have something like:

$query = new EntityFieldQuery;    

$result = $query
     ->entityCondition('entity_type', 'node')
     ->propertyCondition('status', 1) // Getting published nodes only.
     ->propertyCondition('type', 'employees') //Getting 'employees' type only.
     // How do I include custom field as part of query?
     ->execute();

Also, is there an easier way than

$total = count($result); 

to return the COUNT(*) from the query?

1 Answer 1

13

You can use EntityFieldQuery::count(), as reported in the documentation for EntityFieldQuery::execute().

[The result is] Either a number if count() was called or an array of associative arrays of stub entities.

The code you should use is similar to the following one:

$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'employees')
  ->propertyCondition('status', 1) // Getting published nodes only.
  ->count()
  ->execute();

To filter the result by the content type, you need to use EntityFieldQuery::entityCondition('bundle', $content_type).
For conditions on fields, you should use EntityFieldQuery::fieldCondition().

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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