How do I retrieve media from a reference field?
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.
    }
  }