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
Emma Watson 2Emma Watson 2 

Fetching lookup field in apex class?

Hi All,
 
Can anyone please tell me how to fetch the value of staff lookup field of incident object in an apex class.In an incident object, staff lookup field has a value as 'xyz'. How to get this field in an apex class.
 
Please suggest for the same.
 
Thanks!
ManojjenaManojjena
HI Emma Watson ,

I think you Incident is the child object and Staff is a perent object like Contact and Account .
You want to fetch staff name in Incident query .Please check the query I have written for contact and Account .you think that contact is Incident and account is Staff .

SELECT Id,Account.Name FROM Contact .As staff is custom object what you need to write like

SELECT Id,Staff__r.Name FROM Incident__c
Please replace Staff with your Object API name and Incident with your API name .

Let   me know incase any isisue .

Thanks
Manoj
Emma Watson 2Emma Watson 2
Thanks for update...

Here, Incident is an object which has a field named as 'Staff' which is lookup field(User). Staff is not an object here.

So, how to fetch the name of the staff field.
Below is the query that I have written to fetch, but it gives me an id of that staff where I need is a name of the staff.

List<BMCServiceDesk__Incident__c> inc=[SELECT name,BMCServiceDesk__incidentDescription__c,BMCServiceDesk__FKOpenBy__c 
                                         FROM BMCServiceDesk__Incident__c
                                         WHERE BMCServiceDesk__Category_ID__c='Hardware'];
       
        for(Integer i=0;i<inc.size();i++)
        {
            System.debug('Incident name is :'+inc.get(i).name);
            System.debug('Incident description is :'+inc.get(i).BMCServiceDesk__incidentDescription__c);
            System.debug('Incident staff is :'+inc.get(i).BMCServiceDesk__FKOpenBy__c);
        }

The bold one is what giving me Id of the staff but I want it as a name.
Please find the below screenshot for the output.
Staff Id is shown, where I need name of it.

Please suggest.
Thanks!
ManojjenaManojjena
Hi Emma Watson ,

You need to add the Staff field API Name like Staff__r.Name in the query to get the name of the staff .

Let me know in case any issue .

Thanks
Manoj