How to get related list from Trigger.new variable?

trigger TestTrigger on Opportunity (before update){
   for(Opportunity o: Trigger.new){
      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 trigger.new variable has related list? Is my understanding wrong?

Answers:

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

Trigger.new 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.”Trigger.new” 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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x