function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sagar Vavale 4Sagar Vavale 4 

Single Query to fetch parent Role name from current Logged in User

I want to fetch Role name of the Parent Role of current Logged in User in single query

for that currently I am firing 2 queries as follow

UserRole uRole = [Select ParentRoleId, Name, Id From UserRole u where u.Id=:UserInfo.getUserRoleId()];
UserRole Manager_Role = [select Id, Name from UserRole where id=:uRole.ParentRoleId];

 
Shruti SShruti S
Sorry, I dont have an answer for you. Unfortunately you cannot combine these queries into a single query.
NagendraNagendra (Salesforce Developers) 

Hi Sagar,

The Force IDE schema view does not offer a "Foreign Key" (relationship) name for this which usually means that the relationship can't be crossed in a single query and that the Id will have to be used to perform a second query to get the data.

For your reference check with below post:

Hope this helps.

Please mark this as solved if the information helps so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Thanks,
Nagendra
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Sagar Valvale, Hope it will be helpful.

Please mark it as best answer if the information is informative.

Thanks
Rahul kumar
Ajay K DubediAjay K Dubedi
Hi Sagar,
I hope this code will help you: 

Apex Code:
if(UserInfo.getUserRoleId() != NULL){
    Map<Id, UserRole> UserRoleMap = new Map<Id, UserRole>([Select Id, ParentRoleId,  DeveloperName From UserRole Limit 10000]);
    if(UserRoleMap.size() > 0){
        if(UserRoleMap.containsKey(UserInfo.getUserRoleId()) && UserRoleMap.get(UserInfo.getUserRoleId()).ParentRoleId != NULL){
            String ParentRoleName = UserRoleMap.get(UserRoleMap.get(UserInfo.getUserRoleId()).ParentRoleId).DeveloperName;
        	system.debug('>>>>> Name --> '+ParentRoleName);
            
        }
    }
}

User-added image
Points to be Noted:
1. UserRole must exist to getUserId from the UserInfo.
2. If UserRole is more than 10,000 then maybe this code will fail.
3. This code is not under the Best Practices.
4. Salesforce allows 100 Queries, so if you have already 99 Queries then you can go for it otherwise two Queries Best for it.

If you get your answer then mark it as best.
Thank You
Regards
Ajay