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?


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()])
  • How do you reference the child objects? Dec 14 '16 at 18:38
  • o.Child_Objects__r is a list of related records, just iterate through it May 30 '17 at 23:16

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.