+ Start a Discussion
Suresh RaghuramSuresh Raghuram 

soql query to get the users from a subgroup

HI 

I want to check weather a user belongs to specific group or not.
Here Roles are added as groupMembers, I tried as follows but I did not get them. 

Id groupId = [Select Id from Group where Name like 'Home Support' limit 1].Id;

        // store the results in a set so we don't get duplicates
        Set<Id> result=new Set<Id>();
        set<string> grpResult= new set<string>();
        String userType = Schema.SObjectType.User.getKeyPrefix();
        String groupType = Schema.SObjectType.Group.getKeyPrefix();
        String RoleType = Schema.SObjectType.UserRole.getKeyPrefix();
        system.debug('******userType :'+userType+': groupType :'+groupType+': Role Type :'+RoleType);
        // Loop through all group members in a group
        for (GroupMember m : [Select Id, UserOrGroupId From GroupMember Where GroupId = :groupId])
        {
           /* 
            // If the user or group id is a group
            // Note: there may be a problem with governor limits if this is called too many times
            else */if (((String)m.UserOrGroupId).startsWith(groupType))
            {
                // Call this function again but pass in the group found within this group
                //result.addAll(GetUSerIdsFromGroup(m.UserOrGroupId));
                grpResult.add(m.UserOrGroupId);
            }
        }
    system.debug('************USR Ids:'+result+'group Ids :'+grpResult);
     for (GroupMember m : [Select Id, UserOrGroupId From GroupMember Where GroupId IN: grpResult])
        {
             // If the user or group id is a user
            if (((String)m.UserOrGroupId).startsWith(groupType))
            {
                result.add(m.UserOrGroupId);
            }              
        }
    system.debug('************USR Ids:'+result);

Thanks.
pconpcon
I think this will do what you want.  If you query for a Id that does not match the requested object type, you will not get an error, you will just not get any results back.  So you can query all your members, then re-query for any groups that are sub groups of your inital group, and then query for all of your users.
 
Group g = [
    select Id
    from Group
    where Name like 'Home Support'
    limit 1
];

Set<Id> memberIds = new Set<Id>();

for (GroupMember m : [
    select UserOrGroupId
    from GroupMemberId
    where GroupId = :g.Id
]) {
    memberIds.add(m.UserOrGroupId);
}   

for (GroupMember m : [
    select UserOrGroupId
    from GroupMemberId
    where GroupId in :memberIds
]) {
    memberIds.add(m.UserOrGroupId);
}   

Map<Id, User> userMap = new Map<Id, User>([
    select Id
    from User
    where Id in :memberIds
]);

System.debug('User Ids: ' + userMap.keySet());

NOTE: This code has not been tested and may contain typographical or logical errors