Drupal get all entity reference field names by entity type and all parent-child entity ids

First off, sorry the title is so long. Anyway, just try this out and you'll see what it does.
It returns an array containing two arrays: 'settings' and 'children'. Each item in 'children' contains an array of parent node ids. The 'settings' array is like this: [entity type][bundle][field_machine_name].
Slightly modified from: http://drupal.stackexchange.com/questions/40519/how-to-get-the-list-of-all-entit...

<?php
function jeffy_entityreferences_get_parents($child_nids = array(), $bundles = array()) {
  $child_ids = $field_names = $settings = array();
 
  // Get all entityreference field names
  $query = db_select('field_config', 'f');
  $query->fields('f', array('field_name'));
  $query->condition('f.type', 'entityreference');
  $query->distinct();
  $results = $query->execute();
 
  foreach ($results as $result) {
    $field_name = $result->field_name;
    $table = 'field_data_' . $field_name;
    $column = $field_name . '_target_id';
 
    $query = db_select($table, 'f')
        ->fields('f', array('entity_id', $column, 'entity_type', 'bundle'));
    if ($bundles) {
      $query->condition('bundle', $bundles);
    }
    if ($child_nids) {
      $query->condition($column, $child_nids);
    }
    $tmp_results = $query->execute();
 
    foreach ($tmp_results as $tmp_result) {
      $settings[$tmp_result->entity_type][$tmp_result->bundle][$field_name] = $field_name;
      $child_ids[$tmp_result->{$column}]['id'] = $tmp_result->{$column};
      $child_ids[$tmp_result->{$column}]['parents'][$tmp_result->entity_id] = $tmp_result->entity_id;
    }
  }
 
  ksort($child_ids);
 
  return array(
    'children' => $child_ids,
    'settings' => $settings,
  );
}

Tags

Internal References

Article Type

General