How to get related list from variable?

trigger TestTrigger on Opportunity (before update){
   for(Opportunity o:{
      List<Child_Object__c> childObjectList = o.Child_Object__r;
      System.debug('childObjectList size is '+ childObjectList.size());

In the above code the childObjectList size is always printing as zero even though the opportunity object has child objects.

Does it mean that I need to fire SOQL query to get the related list? I thought variable has related list? Is my understanding wrong?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1 only contains a list of the sObject records that the trigger is running on, in this case Opportunities. If you want to get the related records from a different sObject then you’ll need to perform a SOQL query:

for (Opportunity o : [SELECT Id, (SELECT Id FROM Child_Objects__r) FROM Opportunity WHERE Id IN :trigger.newMap.keySet()])

Or query the related records directly:

for (Child_Object__c childRecord : [SELECT Id FROM Child_Object__c WHERE Opportunity__c IN :trigger.newMap.keySet()])

Method 2

Yes you need to fire SOQL query.”” only returns a list of the new versions of the sObject records under context but not the related list records.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x