Add support of NULL values to loadByProperties() and buildPropertyQuery()

Created on 19 April 2024, 2 months ago
Updated 20 April 2024, about 2 months ago

Problem/Motivation

I want to load some entitites by properties, so I intended to use $entityStorage->loadByProperties() to do that. However this approach didn't work for me, I've got an error:
Drupal\Core\Database\InvalidQueryException: Query condition 'flight.company_id IN ()' cannot be empty

The reason is simple - the flight entity has an entity reference field company_id. And I want to get entities where company_id is empty. Looks like EntityStorageBase::buildPropertyQuery() (that is used by loadByProperties()) has no support for null values. So the code like this does not work:

$entities = \Drupal::entityTypeManager()->getStorage('flight')->loadByProperties([
  'bundle' => 'fantastic',
  'year' => 2024,
  'company_id' => NULL,
]);

How can I load entities filtering them by some field that should be empty?

Proposed resolution

I'd suggest to change the behavior of buildPropertyQuery() to add support of `null` like this:

  protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
    foreach ($values as $name => $value) {
      if (is_null($value)) {
        $entityQuery->condition($name, $value, 'IS NULL');
      }
      else {
        // Cast scalars to array, so we can consistently use an IN condition.
        $entityQuery->condition($name, (array) $value, 'IN');
      }
    }
  }

P.S.

If we are talking about some refactoring of loadByProperties(), maybe we could also make it possible to add operator to values for it? For example:

$entities = \Drupal::entityTypeManager()->getStorage('flight')->loadByProperties([
  'year' => [2024, '<='],
  'year' => [2023, '>='],
]);
๐Ÿ› Bug report
Status

Active

Version

10.2 โœจ

Component
Databaseย  โ†’

Last updated about 14 hours ago

  • Maintained by
  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands @daffie
Created by

๐Ÿ‡ท๐Ÿ‡บRussia i-grou

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.69.0 2024