Currently we are using EntityTypeManager to either load or loadMultiple :


This creates and returns objects of nodes which I think uses much resource on the server (since it fetches all fields). We're also trying to fetch around 500 nodes, and each has over 80 fields. We only want to fetch certain fields.

Does anyone know a way to query and fetch only the certain fields needed?

  • I'd rely on the Database API to make a custom query that will fetch only the certain fields you need. See Philipp Zedler's answer in the post mentioned by @leymannx .
    – misterdidi
    Jun 30 at 8:15

You may use a custom query to be more efficient, here is an exemple :

$connection = \Drupal::service('database');
$select = $connection->select('node_field_data', 'n');
$select->fields('n', ['nid', 'type', 'title']);
$select->condition('n.status', 1, '=');
$select->condition('n.type', ['page', 'article'], 'IN');
$select->leftJoin('node__body', 'body', 'body.entity_id = n.nid');
$select->fields('body', ['body_value', 'body_summary']);
$result = $select->execute()->fetchAll(); 
//  print $result[0]->body_value; 

You have to join table for each field you need to get. Note that $result does not contain hydrated Node objects but stdClass; this could work with all kind of database entities (i.e User or whatever).

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