How to run entity field query in cron without getting undefined stdClass::$roles notice? I've got a cron job which executes an entity field query to count the number of some nodes associated with a user (for each user in the system). Whenever this runs I get the following in the watchdog logs:


  Notice: Undefined property: stdClass::$roles in user_access() (line 820 of […]/Drupal/modules/user/user.module).


Is there anything specific I need to do to avoid this happening (not involving changing log levels or otherwise ignoring the issue)? Any particular best practices when using Drupal queries outside the context of a "real" session? The reason I'm doing this is to get rid of any spurious noise in the logs, and reduce the chance of breaking things in case of change to both my own and Drupal code.

Query code:

$q = $query-&gt;entityCondition('entity_type', 'node')
    -&gt;entityCondition('bundle', $content_types, 'IN')
    -&gt;propertyCondition('status', 1)
    -&gt;propertyCondition('uid', $uid)
    -&gt;propertyCondition('type', $content_types, 'IN')
    -&gt;fieldCondition('field_something', 'value', $code, '=');

$award_count = $q-&gt;count()-&gt;execute();


Stack trace:

[…]/Drupal/modules/node/node.module(3334): user_access('bypass node acc...', Object(stdClass))
[…]/Drupal/modules/node/node.module(3296): _node_query_node_access_alter(Object(SelectQuery), 'entity')
[…]/Drupal/includes/module.inc(1163): node_query_entity_field_access_alter(Object(SelectQuery), NULL, NULL, NULL)
[…]/Drupal/includes/database/select.inc(1253): drupal_alter(Array, Object(SelectQuery))
[…]/Drupal/includes/database/select.inc(1261): SelectQuery-&gt;preExecute()
[…]/Drupal/includes/database/select.inc(1275): SelectQuery-&gt;preExecute()
[…]/Drupal/includes/entity.inc(1389): SelectQuery-&gt;execute()
[…]/Drupal/modules/field/modules/field_sql_storage/field_sql_storage.module(652): EntityFieldQuery-&gt;finishQuery(Object(SelectQuery), 'entity_id')
[internal function]: field_sql_storage_field_storage_query(Object(EntityFieldQuery))
[…]/Drupal/includes/entity.inc(1216): call_user_func('field_sql_stora...', Object(EntityFieldQuery))
[…]/[my code path]: EntityFieldQuery-&gt;execute()


Running Drupal 7.56.
As you can see in the cron doc, cron runs as anonymous user so you have to run the query as admin user. 

In the EntityFieldQuery DO doc you can see examples, but essentially you just need to add the addMetaData code to the end  of your query:

 $q = $query-&gt;entityCondition('entity_type', 'node')
    -&gt;entityCondition('bundle', $content_types, 'IN')
    -&gt;propertyCondition('status', 1)
    -&gt;propertyCondition('uid', $uid)
    -&gt;propertyCondition('type', $content_types, 'IN')
    -&gt;fieldCondition('field_something', 'value', $code, '=')
    // Run the query as user 1.
    -&gt;addMetaData('account', user_load(1));