How do I load a Media entity from a File entity?
Question
I have a File entity loaded programmatically. I want to load a Media entity from it. Is there a way to achieve this?
Solution
Example - if your File
entity is loaded in a variable named $file
, and the field name on the Media
entity is field_media_image
:
$media_entities = \Drupal::entityTypeManager()->getStorage('media')->loadByProperties([
'field_media_image' => $file->id(),
]);
$media_entity = is_array($media_entities) ? array_pop($media_entities) : NULL;
Note1 : If the File
object belongs to more than a single Media
entity, you will need to loop through $media_entities
to find the one you want.
Note 2: $media_entity
will either contain the Media
entity the File
entity belongs to, or be NULL
if the File
entity doesn't belong to a Media
entity.
OTHER TIPS
Actually i found a good answer, i used :
$result = \Drupal::service('file.usage')->listUsage($file);
and then in the $result i am checking if any keys called media
exist. If so, i can then load my Media :)