Is there a performance way to count group users and members without using an static query?

Currently I'm using this and works:

$connection = \Drupal::database();

$query = $connection->query('SELECT count(id) as count FROM {group_content_field_data} WHERE gid = :id AND type LIKE :type', [
  ':id' => $group->id(),
  ':type' => $group->getGroupType()->id() . '-group_node-%',
]);
$count_contents = $query->fetchAll();

$query = $connection->query('SELECT count(id) as count FROM {group_content_field_data} WHERE gid = :id AND type LIKE :type', [
  ':id' => $group->id(),
  ':type' => $group->getGroupType()->id() . '-group_membership-%',
]);
$count_users = $query->fetchAll();

Static quering not seems a secure long-term approach, but If I use other ways like count getContents I totally lost performance:

$count_contents = count($group->getContent());
$count_users = count($group->getMembers());

It's there other performance way using entity query?

Comments

oriol_e9g created an issue.

robertragas’s picture

Currently experiencing the same issue, in my case I have a group with over 10k members and this times out every time.

jpoesen’s picture

Not sure if it's more performant or not, but I used this in the past:

$group_memberships = \Drupal::service('group.membership_loader')->loadByGroup($group);
$num = count($group_memberships);
ydahi’s picture

Hi guys, this is really helpful, thanks! Silly question: If I wanted to include a count of members or nodes in a view block, where would I add this code to?

zcht’s picture

the YASM module also displays very detailed statistics for groups and users. could you have a look how it is done there, just as a hint :)

ydahi’s picture

Thank you! Exactly what I was looking for