For a given taxonomy term in D8, is there any API function/method that returns all node entities that reference it?
4 Answers
You can use loadByProperties()
to get all node entities that reference $term_id
:
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
'field_tags' => $term_id,
]);
Easiest way I think is to query database taxonomy_index
table keeps record of what node is tagged with what term
function _get_nodes_by_term($term_id) {
$query = \Drupal::database()->select('taxonomy_index', 'ti');
$query->fields('ti', ['nid']);
$query->condition('ti.tid', $term_id);
$nodes = $query->execute()->fetchAssoc();
return $nodes;
}
dpm(_get_nodes_by_term(<term_id>));
Drupal Core does it by views.
Out the box term page display is created by views so if you visit admin/structure/views/view/taxonomy_term
, this view is responsible to show all tagged content by given term, which is essentially running database query.
If you have multiple term ids you can pass an array of the ids instead of just a single value.
$term_ids = array (1,2,3);
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
'field_tags' => $term_ids,
]);
If your nodes not having revision then this code will work, by default it will return the first revision
$nodes = \Drupal::entityTypeManager()->getStorage('node')->getQuery()
->condition('field_tags', $termId)
->execute();
If your nodes have multiple revisions, To get the nodes by the latest tagged revision. you need to use the following code
$nodes = \Drupal::entityTypeManager()->getStorage('node')->getQuery()
->latestRevision()
->condition('field_tags', $termId, '=')
->execute();
if you have multiple values then you can use array
$termIds = [3,56,456];
$nodes = \Drupal::entityTypeManager()->getStorage('node')->getQuery()
->latestRevision()
->condition('field_tags', $termIds)
->execute();