Score:0

Optimize fetching data from entity objects

cn flag

Currently we are using EntityTypeManager to either load or loadMultiple :

$this->entityTypeManager->getStorage('node')->loadMultiple($nids);
$this->entityTypeManager->getStorage('node')->load($nid);

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?

misterdidi avatar
de flag
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 .
Score:2
pt flag

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).

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.