2

I have a file and I know there is a media that references it. How can I get this media?

In the opposite direction, knowing the media id, I can get the file:

$media = Media::load($mid);
$fid = $media->field_media_image->target_id;
$file = File::load($fid);

But now I know the file id and I want the media. How can I get it?

1

1 Answer 1

4

You can use entityQuery:

$fid = 13141;
$usedIn = \Drupal::entityQuery('media')
  ->condition('field_media_image.target_id', $fid)
  ->execute();

Example response:

Array
(
    [15105] => 13109
)

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.