I have a Node by the Project bundle name.

Each Project has a reference field to another entity by the name of Contact, that this contact entity has the Client bundle.

I can get the Client target ID from the node.

I want to search in the hole of the Nodes and find those nodes that this Client set in the reference field

Then How I should 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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