I have a Project content type, which has a reference field to a Contact entity that has a Client bundle.

I can get the reference target ID from the node. I want to find the nodes that contain a reference to Client entities.

How should I be able to search in the node reference field target IDs to find the similar?


Use entityQuery to search for referenced entities.

Let’s illustrate a couple of examples of querying for node entities using this object.

A very simple query that returns the published nodes:

function ecc_general_node_update(Node $node) {
    // Find the project for current client that are actives
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('field_project_status', 'Active')
      ->condition('field_client', $node->field_client->target_id);
    $searchNodes = $query->execute();

The out put looks like this, just the nodes IDs appears:

array (size=2)

106 => string '101' (length=3)

109 => string '104' (length=3)


This is often achieved using Views with a Contextual filter that pulls in the current node ID and uses it as the "parent" to find the "children" of that Entity Reference field.

Here is a similar question/answer with all the steps how to set it up:
List "ER Child" info on "ER Parent" nodes

Using Views is often the more maintainable solution. Using custom queries is sometimes used when Views query performance isn't good enough and needs to be optimized.

Not the answer you're looking for? Browse other questions tagged or ask your own question.