I have the file ID (fid), and the rest of the file object.

I need to get fields from the parent media entity, but I can't find anything about loading a media entity from a file object.

Drupal 8.4.0


I asked this question in relation to another: Media name as link to file

As far as I could find Kevin's comment is correct.

  • The File object won't have a reference to a Media entity using it. You need to load the Media entity and access the file that way.
    – Kevin
    Nov 11, 2017 at 0:15
  • Just realised I didn't say what version of Drupal I'm on. @Kevin, it that for D8? Nov 13, 2017 at 9:57
  • 1
    Wouldn't a file entity be related to a media entity via an entity reference field? And doesn't core have reverse entity reference field logic built-in? Feels like you should be able to get that pretty easily
    – Clive
    Nov 15, 2017 at 14:25
  • @Clive, exactly my thoughts, I guess it's that logic I'm asking about. Nov 15, 2017 at 14:57

4 Answers 4


Using the service file.uses you get the file media object:


$file is a loaded file object.
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

$result should now contain an array like so:

$result['file']['media']['4372'] = 2;

Where 4372 is the media id. and 2 the times the file is used.

From the docs of listUsage:

@return array
   *   A nested array with usage data. The first level is keyed by module name,
   *   the second by object type and the third by the object id. The value of
   *   the third level contains the usage count.

I recently needed to do the same, and came up with the following. First, load the file entity from the fid:

$fid = 1000;
$file = \Drupal\file\Entity\File::load($fid);

Then, call file_get_file_references on the file entity:

$references = file_get_file_references($file);

Per the docs, you will get back a nested array of the referencing field names, entity types, entity ids, and finally the referencing entity itself.

use Drupal\media\Entity\Media;
use Drupal\node\Entity\Node;

function myFunction() {
  $node_load = Node::load($nids);
  $media_field = $node_load->get('media_field_machine_name')->getString();
  $media_entity_load = Media::load($media_field); 
  $uri = $media_entity_load->field_media_video_file->entity->getFileUri(); 
  $banner_media_url = file_create_url($uri);

$file is a the loaded file object.

$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

Is very relevant answer and more optimized result.

  • Thank you for your answer; maybe you could indicate the difference with the one answered by FLY?
    – Watergate
    Sep 20, 2022 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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