EntityFieldQuery with isNull/isNotNull workaround

Public

I needed to add a entity reference field to a preexisting content type. I then needed to populate the field programmatically as the nodes were created. I had to use a hook_query_TAG_alter() in order to query null entities. This is apparently the only way to use the isNull/isNotNull methods with an EntityFieldQuery.

Get raw version
php
  1. /**
  2.  * Implements hook_query_TAG_alter().
  3.  */
  4. function myModule_query_is_null_alter(QueryAlterableInterface $query) {
  5. // We want to query entities that are NULL. This is the only way to leftJoin on an entity query in D7.
  6. $query->leftJoin('field_data_field_myfield', 'dsr', 'node.nid = dsr.entity_id');
  7. $query->isNull('dsr.field_data_myfield_target_id');
  8. }
  9.  
  10. function myModule_query() {
  11. $query = new EntityFieldQuery();
  12. $result = $query->entityCondition('entity_type', 'node')
  13. ->entityCondition('bundle', 'contentType')
  14. ->propertyCondition('status', 1)
  15. ->addTag('is_null') // Querying NULL entities.
  16. ->propertyOrderBy('created', 'DESC')
  17. ->execute();
  18.  
  19. if (isset($result['node'])) {
  20. $nids = array_keys($result['node']);
  21. $nodes = entity_load('node', $nids);
  22. return $nodes;
  23. } else {
  24. watchdog('myModule', 'No rows to be returned.');
  25. }
  26. }