I have a File entity loaded programmatically. I want to load a Media entity from it. Is there a way to achieve this?
Example - if your
File entity is loaded in a variable named
$file, and the field name on the
Media entity is
$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.
$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