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
Jonathan Meltzer 14Jonathan Meltzer 14 

Lookup field populated but lookthrough is not working in APEX

I will try to generalize this question, as I believe that the issue is not related to the specific objects.  I have an object (call it Object1) that has a Lookup field called Lookup1__c.  The Lookup field looks to another object called Object2__c.  Object2__c has an ID field and a custom field called Field2__c.

When I retrieve a record for Object1, I see a value in the Lookup1__c field - it is an ID.  However, when I try to retrieve Object1.Lookup1__r.ID or Object1.Lookup1__r.Field2__c, all I get are NULL values.  The query is not looking through to Object2, even though the relationship is valid and Developer Console does not show any errors.

Any ideas?  How do I get the Object1.Lookup1__r.Field2__c value, once I am on the Object1 record?
Best Answer chosen by Jonathan Meltzer 14
Steven NsubugaSteven Nsubuga
Are you doing this in a trigger? If so then yeah, that would be the expected behaviour. You would have to explicitly write SOQL to retrieve those values.
In case my guess is wrong, supply more information about what exactly you are doing and how. Share some code or even pseudo code for your scenario.

All Answers

Steven NsubugaSteven Nsubuga
Are you doing this in a trigger? If so then yeah, that would be the expected behaviour. You would have to explicitly write SOQL to retrieve those values.
In case my guess is wrong, supply more information about what exactly you are doing and how. Share some code or even pseudo code for your scenario.
This was selected as the best answer
Jonathan Meltzer 14Jonathan Meltzer 14
I am doing this in a trigger, and I actually was retrieving via SOQL as I read your answer, and it worked!  Thank you for the reply.  Why do triggers not work that way, though?  What is it that I have missed?  I have done a lot of APEX coding and trigger coding, and I don't recall anything that says you cannot do what I am trying to do.  
Steven NsubugaSteven Nsubuga
My guess is that it is Salesforce's way of lazy loading. For it to work that way would require Salesforce to load all the fields of Object2 such that they can immediately be summoned via Object1.Lookup1__r.FieldName__c. So if Object2 has 200 fields all of them would have to be available just in case you need 1 of them (coz the system cannot know in advance which ones you will need).