8

Problem :

I need filtering entities based on the value of a multiple-choice field.
I want my query returns all entities except those who have a given value ('doe' for this example).

Actual :

multiple-choice values

foo|Choice 1
bar|Choice 2
doe|Choice 3

MyController.php

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

Need :

So I need something like below :

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

How can I do ? Thank you in advance.

2 Answers 2

16

I found it !

Just 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);

As the doc says, public function QueryInterface::condition take following arguments :

condition( $field , $value = NULL , $operator = NULL , $langcode = NULL )
1
  • 5
    Note that the correct database operator for 'not equal to' is '<>'
    – Darvanen
    Commented Apr 11, 2019 at 23:03
5

It is impossible to check for the existence of entities with field <> value if that field may be null.

Instead, 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();

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.