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, '>='],
]);