0

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->select('media_field_data', 'm')
->fields('m', ['mid'])
->condition('m.bundle', 'gallery')
->leftjoin('node__field_related_gallery', 'n', 'media_field_data.mid = node__field_related_gallery.field_related_gallery_target_id')
->leftjoin('field_related_gallery_media_field_data', 'd', 'node__field_related_gallery.entity_id = field_related_gallery_media_field_data.nid')
->range(0, 5)
->execute()
->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.

0

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()->getParameter('node');

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.