I have an entity (a node) with a term reference field. I'd like to access the referenced term entities programmatically, i.e. the fully loaded term objects.
Note that my question could equally apply to any referenced entity, e.g. node entities, user entities, etc.
Here's what I've got so far:
$node = \Drupal\node\Entity\Node::load($nid);
$term_ids = array();
$items = $node->field_tags->getValue();
foreach ($items as $item) {
$term_ids[] = $item['target_id'];
}
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($term_ids);
It works, but I'm not very happy with it:
- It lacks abstraction (how am I supposed to know that the id of the referenced entity is in
$item['target_id']
?) - It's not very generic (it works if the field references terms, but what if it references nodes or users?
Any better solution?