Drupal 11: Load Media Entity By File ID

In Drupal, you can load a media entity by its associated file ID using loadByProperties() on the media storage. The key is to query the field that references the file, which depends on the type of media item you are looking for.

Using the entity type manger service we can load the media item using the field that stores the file.

// Load the media storage.
$mediaStorage = \Drupal::entityTypeManager()->getStorage('media');

// For an image media type (field_media_image is the default field name):
$mediaEntities = $mediaStorage->loadByProperties([
  'field_media_image.target_id' => $fileId,
]);

// For a document/file media type (field_media_document or field_media_file):
$mediaEntities = $mediaStorage->loadByProperties([
  'field_media_document.target_id' => $fileId,
]);

// Get the first match (if any).
$media = reset($mediaEntities) ?: NULL;

The field name depends on the media type. Common defaults are:

  • field_media_image — for the "Image" media type
  • field_media_document or field_media_file — for the "Document"/"File" media type
  • field_media_video_file — for the "Video" media type

The .target_id suffix targets the file entity reference column specifically.

Finding The Source Field Name

If you don't know the media type in question then you can use the entity type manager service to find this out.

/** @var \Drupal\media\MediaTypeInterface $mediaType */
$mediaType = \Drupal::entityTypeManager()->getStorage('media_type')->load('image');
$sourceFieldName = $mediaType->getSource()->getSourceFieldDefinition($mediaType)->getName();
// Then use $sourceFieldName . '.target_id' in your query.

Entity Query

An alternative to using the entity type manager directly is to use the entity query service.

$query = \Drupal::entityQuery('media')
  ->condition('field_media_image.target_id', $fileId)
  ->condition('bundle', 'image')
  ->accessCheck(FALSE)
  ->range(0, 1);

$ids = $query->execute();

if ($ids) {
  $media = \Drupal::entityTypeManager()->getStorage('media')->load(reset($ids));
}

This will give you a single media item.

Add new comment

The content of this field is kept private and will not be shown publicly.