Drupal 10: Find All Groups That Contain A Given Node

Use this to load all groups that are linked to a given node ID.

/**
 * Given a node, find the group IDs that the node is a part of.
 *
 * @param int $nid
 *   The node ID.
 *
 * @return array
 *   An array of group IDs that the node is present in.
 */
 function getGroupIdsByEntity($nid) {
  $query = \Drupal::database()->select('group_relationship_field_data', 'gr');
  $query->innerjoin('groups_field_data', 'gfd', 'gr.gid = gfd.id');
  $query->condition('gr.entity_id', $nid);

  // Don't include group user memberships in the query.
  $query->condition('gr.type', 'group-group_membership', '!=');

  $query->fields('gr', ['gid']);
  $result = $query->execute();

  $groupIds = [];
  foreach ($result as $record) {
    $groupIds[] = $record->gid;
  }
  return $groupIds;
}

Note that this code makes the assumption that your group relationships are simple. Nodes are linked with the relationship type of "group-group_node-[content-type]" and the plugin ID of "group_node:[content-type]", where [content-type] would be "article" or "page". By simply removing the memberships we are selecting for content items in this query. If you have other relationships in your groups then you might need to alter the condition to be a like comparison.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
10 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.