Filtering entities with EntityQuery using "Is Not Equal To" condition

In this blog post, we will discuss how to filter entities based on the value of a multiple-choice field using EntityQuery in Drupal. The goal is to return all entities except those with a given value ('doe' in this example).

Problem

Actual :
multiple-choice values
foo|Choice 1
bar|Choice 2
doe|Choice 3

$nodeStorage = \Drupal::entityManager()->getStorage('node');
$nids = $nodeStorage->getQuery()
->condition('type', 'order')
->execute();
$entities = $nodeStorage->loadMultiple($nids);

Solution

Reverse the last two parameters of the condition function and use the '<>' operator.

$nodeStorage = \Drupal::entityManager()->getStorage('node');
$nids = $nodeStorage->getQuery()
       ->condition('type', 'order')
       ->condition('field_multiple_choice', 'doe', '<>')
       ->execute();
$entities = $nodeStorage->loadMultiple($nids);

Note that the correct database operator for 'not equal to' is '<>'. If the field may be null, you must use an orCondition to do notExists OR <>:

$query= Drupal::service('entity.query')->get('myentity');
$group = $query->orConditionGroup()
->notExists('my_field')
->condition('my_field', '53', '<>');
$ids = $query->condition($group)->execute();

By using EntityQuery with the appropriate conditions, you can effectively filter entities based on the value of a multiple-choice field.

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!