How do I retrieve media from a reference field? Inside a node type, I have a reference field to target a media.
With a db select, I need to load all related medias of the nodes.
For this I use this code: 

$database = \Drupal::database();
$result = $database-&gt;select('media_field_data', 'm')
-&gt;fields('m', ['mid'])
-&gt;condition('m.bundle', 'gallery')
-&gt;leftjoin('node__field_related_gallery', 'n', 'media_field_data.mid = node__field_related_gallery.field_related_gallery_target_id')
-&gt;leftjoin('field_related_gallery_media_field_data', 'd', 'node__field_related_gallery.entity_id = field_related_gallery_media_field_data.nid')
-&gt;range(0, 5)
-&gt;execute()
-&gt;fetchAllKeyed(0, 0);
dpm($result);


But with this code I get an error and don't get the related mids. If I remove the line with the leftjoin I get the mids.

How can I proceed to verify if a media is related to a node and get only the media with a related node?

With views I can get easily the results with this query:

SELECT media_field_data.mid AS mid, 
field_related_gallery_media_field_data.nid AS 
field_related_gallery_media_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {node__field_related_gallery} node__field_related_gallery ON 
 media_field_data.mid = 
 node__field_related_gallery.field_related_gallery_target_id AND 
 node__field_related_gallery.deleted = '0'
 LEFT JOIN {node_field_data} field_related_gallery_media_field_data ON 
 node__field_related_gallery.entity_id = 
 field_related_gallery_media_field_data.nid
 WHERE (media_field_data.status = '1') AND (media_field_data.bundle IN 
 ('gallery')) AND (field_related_gallery_media_field_data.nid IS NOT NULL)
 LIMIT 26 OFFSET 0


Thanks.
Do you have to do it with a DB call? Why not use Drupal's existing functions?

  // Load a node by node ID.
  $nid = '213';
  $node = \Drupal\node\Entity\Node::load($nid);

  // OR load current node.
  $node = \Drupal::routeMatch()-&gt;getParameter('node');

  if (!empty($node)) {
    // Assumes you have a media field called "Related gallery"
    $medias = $node-&gt;get('field_related_gallery')-&gt;referencedEntities();

    foreach ($medias as $media) {
      // Do stuff with the media.
    }
  }