Extending the Node Query in Drupal 8: Fetching All Related Fields

In this article, we delve into how to fetch nodes in Drupal 8 based on a specific taxonomy term and retrieve all related fields for each node. This powerful feature allows for a deeper data analysis and a more comprehensive understanding of your site’s content.

Step 1: Fetch Nodes by Category Term

First, we’ll fetch nodes based on a taxonomy term. Here’s how you do this:

$term_id = // The taxonomy term ID;
$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('field_tags', $term_id);
$nids = $query->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

Step 2: Retrieve All Related Fields for Each Node

Next, we’ll iterate over each node to access its fields:

foreach ($nodes as $node) {
  $title = $node->getTitle();

  foreach ($node->getFields() as $field_name => $field) {
    // Process each field

  if ($node->hasField('field_related_nodes')) {
    $related_nodes = $node->get('field_related_nodes')->referencedEntities();
    foreach ($related_nodes as $related_node) {
      // Process each related node

Field Processing

Fields in Drupal can vary in types, so they require different methods to retrieve their values.

For example:

Text field: $node->get(‘field_name’)->value
Image field: $node->get(‘field_image’)->entity->getFileUri()

Bonus: Utilizing Drupal’s Field Definitions

To gain more insights into available fields and their types, use field definitions:

$field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', $node->bundle());
foreach ($field_definitions as $field_name => $field_definition) {
  $field_type = $field_definition->getType();
  // Other processing

By fetching nodes based on category terms and processing all related fields, you can significantly enhance your Drupal 8 site’s functionality. This method allows for a more dynamic and content-rich experience.

Remember, always tailor your code to fit your specific site architecture and data structure. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *