1

The following fails with an exception.

\Drupal::entityTypeManager()->getStorage('foo_module_division')->loadByProperties(['enabled'=>TRUE, 'parent_code'=> NULL]).

How else do I specify I want to load entities whose parent_code field is NULL?

2 Answers 2

0

The exception is the result of how EntityStorageBase::loadByProperties() builds the underlying WHERE clause; it's utilizing ::buildPropertyQuery() which casts NULL to an array then uses the IN operator to compare; this won't work since you need a IS NULL query to find NULL entries in the DB.

Instead, you can build your own entity storage query in a similar way as loadByProperties():

$es = \Drupal::entityTypeManager()->getStorage('foo_module_division')
$q = $es->getQuery();
$results = $q->condition('parent_code', NULL, 'IS')->condition('enabled', TRUE)->execute();
return $results ? $es->loadMultiple($results) : array();
2
  • Many thanks Shawn. Works great for me. Thanks for the detailed explanations - would probably have never known main cause for error
    – ilechcod
    Commented Apr 1, 2020 at 8:30
  • 2
    For anybody who stumbles across this on Drupal 9 or 10, the condition for IS NULL is now written like so; condition('parent_code', '', 'IS NULL')
    – Christian
    Commented Aug 2, 2023 at 7:54
3

The example of getting articles that has empty body:

  $entityStorage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $entityStorage->getQuery();
  $query->condition('type', 'article');
  $query->notExists('body');
  $nids = $query->execute();
  $nodes = $entityStorage->loadMultiple($nids);
1

Your Answer

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

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