How to find where media entity is used?

Components

To find out where a media entity is used on your Drupal site, you can use the following query. Just replace the $media_id with your Media ID and execute the query.

$media_id = YOUR MEDIA ID;

// Get all media fields.
$media_fields = \Drupal::entityTypeManager()->getStorage('field_storage_config')->loadByProperties([
  'type' => 'entity_reference',
  'settings' => [
    'target_type' => 'media',
  ],
]);

// Get a query for each field table.
$queries = [];

foreach ($media_fields as $media_field) {
  $name = $media_field->getName();
  $entity_type = $media_field->get('entity_type');
  $table_name = "{$entity_type}__{$name}";
  $query = \Drupal::database()->select($table_name, 'T');
  $query->fields('T', ['entity_id', "{$name}_target_id"]);
  $query->where("{$name}_target_id = :id", [':id' => $media_id]);
  $result = $query->execute()->fetchAll();
  dsm($entity_type);
  dsm($result);
}

The easiest way to execute this query is probably in Devel PHP. 

About the Author

Goran Nikolovski is a senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.