2

I need to select some entities that have a certain field (user reference) empty or that field does not contain the current user as a reference.

I tried this. It works fine if the field is empty or if the field contains exactly one value. For multiple values, it displays the wrong value.

$query = $this->entityTypeManager()
  ->getStorage('my_entity_type')->getQuery();
$group = $query->orConditionGroup()
  ->notExists("my_field")
  ->condition("my_field", \Drupal::currentUser()->id(), "<>");
$query->condition($group);
$query->condition("type", "my_bundle_id");

What changes should I do to my code to make it work with a multi-value field?

0

1 Answer 1

0

Use NOT IN instead of <>.

$query = $this->entityTypeManager()
  ->getStorage('my_entity_type')
  ->getQuery();
$group = $query->orConditionGroup()
  ->notExists("my_field")
  ->condition("my_field", \Drupal::currentUser()->id(), "<>");
$query->condition($group);
$query->condition("type", "my_bundle_id");

Your Answer

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

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