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
Eli Flores, SFDC DevEli Flores, SFDC Dev 

Trigger can't reference child fields

I'm having a problem efficiently getting related field in a trigger. I have the following code

System.debug('User Contact ID='+myRecord.Time_Clock__r.Team_Member_Employee__c);
System.debug('Time Clock ID='+myRecord.Time_Clock__c);
Time_Clock__c myTimeClock = [select id,Team_Member_Employee__c from Time_Clock__c where Id=:myRecord.Time_Clock__c];
System.Debug('On Object Team_Member_Employee = '+myTimeClock.Team_Member_Employee__c);


And this is the result from the debug log


07:16:56.035 (35542000)|USER_DEBUG|[5]|DEBUG|User Contact ID=null
07:16:56.035 (35594000)|USER_DEBUG|[6]|DEBUG|Time Clock ID=a0gV00000008YBUIA2
07:16:56.047 (47935000)|USER_DEBUG|[10]|DEBUG|On Object Team_Member_Employee = 003V0000005F2uRIAS


My Question is why am I getting Null as Id in the first (myRecord.Time_Clock__r.Team_Member_Employee__c) get the correct Id in the3rd (instantiate a new Time_Clock__c then get Team_Member_Employee__c)?


Is there some trick to making myRecord.Time_Clock__r.Team_Member_Employee__c not null and in line with 3rd?


I need to run a further SOQL statement based on the Team_Member_Employee__c field and I'd like to avoid have two SOQL queries for one trigger pass. 

Cory CowgillCory Cowgill

If you want related field for a record in a trigger, you have to query for the related fields.


Triggers, to stay efficient in a multi-tenant environment, do not pull in all the related records information. If you want the related record information, you have to Query for the information.


You can perform Relationship Queries to pull in the data in one SOQL query, but you'll need to perform at least one SOQL query to get those related fields.