5

On one of my content types I have a taxonomy term reference field that allows for multiple values. Normally if I wanted the term from a field I'd simply do

$node->field_taxonomy_term->entity;

However this doesn't work if there are multiple entities. Normally I would expect getValue() to do the trick but that just gives an array of the ids with target_id as the key. I sort of have a round about way of getting them with this method

    $entity_storage = \Drupal::entityTypeManager()->getStorage('taxonomy');
    $ids = [];
    foreach ($this->field_taxonomy_term->getValue() as $item) {
        $ids[] = $item['target_id'];
    }
    $entities = $entity_storage->loadMultiple($ids);

But when getting one is as simple as $node->field_name->entity I had a feeling that I'm doing more work than necessary. Is there a simpler way to obtain an array of entities from a field or is what I'm doing the most efficient way to do it?

1 Answer 1

7

I can't say for sure on that specific field but usually there's the referencedEntities() method you can call

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AreferencedEntities/8.4.x

So something like this perhaps:

$entities = $node->field_taxonomy_term->referencedEntities();

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.