2

I have seen this code suggesting how to return a list of entity IDs:

$query = \Drupal::entityQuery('node');
$query->condition('type', $bundle);
$entity_ids = $query->execute();

but this requires the knowledge of when to use "type" or what "type" is. For example, for user entity i would think setting type to $bundle = 'user' would work - but it gives error.

for terms from a vocab i would expect type to be set to the name of the vocab; but that also gives an error.

Is there a generic method to call for entity_type that would hint at what is required to do a query for entity ids?

1 Answer 1

1

You're looking for the bundle key, which can be obtained from the entity type:

$entity_type = 'node';

// Load the entity type definition and get its keys.
$keys = \Drupal::entityTypeManager()
  ->getDefinition($entity_type)
  ->getKeys();

$query = \Drupal::entityQuery($entity_type);

// 'bundle' is optional, if not provided it will be the same as the entity type ID, 
// but obviously you won't need to use it as a condition.
if (mb_strlen($keys['bundle'])) {
  $query->condition($keys['bundle'], $bundle);  
}

$entity_ids = $query->execute();

See EntityType::getKeys() for more information.

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.