I am writing some drush scripts and find myself needing to get related entities (nodes) of the current node. However I can only find info for constructing views that do this.

Can anyone tell me is there a programmatic way to pull all entities that relate to the current nid with a filter on the entity type?

Ultimately I need to get a list of node ids that relate to the current node id.

The relationship depend on the relation module.

  • You should mention how your nodes are related to one another to get the answer you're looking for. For example, are you using the Relation or Entity Reference module? – Shawn Conn Jun 20 '16 at 1:55
  • @shawn-conn Good point. It's using the Relation module. – dibs Jun 20 '16 at 2:48
  • To me it would be a db_query (through a script, module or theme) including the reference field and the row result would return the entity_target_id – mchar Jun 20 '16 at 9:52
  • @mchar It is looking that way. I'm writing some not so efficient queries to the field_data_endpoints table that seem to be delivering good results. – dibs Jun 20 '16 at 21:30

Like this, you will get all the referenced items of the node being displayed.

  $current_path = explode('/', $_GET['q']);
  if ($current_path[0] == 'node' && is_numeric($nid = $current_path[1])) {
    $field = 'my_field';
    $bundle = 'my_bundle';
    $query = db_query("SELECT {$field}_target_id FROM field_data_{$field} WHERE entity_id = :nid AND bundle = :bundle",
        ':nid' => $nid,
        ':bundle' => $bundle,
    foreach($query as $row) {
      $target_ids[] = $row->{$field . "_target_id"};
    $nodes = node_load_multiple($target_ids);

If you have more entity reference fields, you have to expand the query (with more joins) according to your fields.

  • I am writing some drush scripts so I don't have the current path. Also I think to find the related nodes you only really need to query the "field_data_endpoints" table when all your content it related via the relations module. – dibs Jun 23 '16 at 2:07
  • The current path can be anything, this is just an example, to your script it could be another query fetching all nids. The node table isn't needed, yes. – mchar Jun 23 '16 at 11:57

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.