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 ok if the field is empty or if the field contains exactly one value. For multiple values it displays a wrong output:

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

$ids = $query->sort(...)->execute();

Any thoughts on how to make this work?

  • Did my answer help you?
    – user72672
    Jan 3 '20 at 18:39

Try to use NOT IN instead of <>.

->condition("my_field", [\Drupal::currentUser()->id()], "NOT IN");

You can learn more here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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