1

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?

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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