I need to get a list of all users that have a specific role. Those users can be referenced in a multivalue field of a specific content type; some users are referenced in multiple nodes of that content type, some in none. I want to filter out all users that are not referenced in any node of that content type. Here's my current (functional) code:
$ids = \Drupal::entityQuery('user')
->condition('status', 1)
->condition('roles', 'dozent')
->sort('field_name', 'ASC')
->execute();
foreach($ids as $k => $id){
$references = \Drupal::entityQuery('node')
->condition('type', 'angebot')
->condition('field_dozenten', $id)
->count()
->execute();
if(intval($references) === 0) unset($ids[$id]);
}
This works as intended as far as I can tell, but performant-wise it seems quite inelegant due to the large amount of database queries. Is there a better way? Can I somehow include the condition that a user must be referenced in at least one node in the first entityQuery? If not, is there a more performant way to perform the second query (e.g. a way to only search for the first reference from a node to the user, since I don't need the exact count anyway)? I'm open to other suggestions as well.