Score:1

Get field value from multiple entities at once

ar flag

I have a Drupal site using paragraphs in which one of the content types, let's call it a Group, can contain any number of paragraphs, and each of these paragraphs, let's call them Members, contains a reference to a user. I want to get all the uids of users which are Members of a given Group.

I could accomplish this with a query of the database like

SELECT field_user_target_id
FROM paragraph__field_user
WHERE entity_id = (
    SELECT field_members_target_id
    FROM node__field_members
    WHERE entity_id = <GroupID>
    LIMIT 1
);

for a given GroupID, but I'm wondering if there's a way to do this efficiently without directly querying the database. One option would be something like

$group = \Drupal\node\Entity\Node::load($groupID);
$uids = [];
foreach ($group->field_members->referencedEntities() as $member) {
    $uids[] = $member->field_user->target_id;
}

but is there a way to do this without having to loop through the Members?

Score:3
cn flag

The foreach loop is how I would do it, but to your point, a query will usually be the most efficient. This technically applies in any situation where you have an API layer in between. If you would rather craft a query you can do so, but generally is not required. When profiling you application, if this area becomes a bottleneck, that is when I would start considering doing something like that. Note that using the API handles things like revisions and all that other stuff.

See Drupal 8: how can I "eager load" Entities referenced via EntityReferenceFieldItemList field for further details. In that post they explain that using referencedEntities() loads those entities into memory, so it is not like these are individual hits on the database.

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.