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
ShayneOShayneO 

Best Practices for Querying Inside a Trigger

Hello - I'm fairly new to Apex and am hoping I could get some help/examples of how to properly query data from related objects inside of a trigger.

Essentially, my scenario is as such:

Objective - Whenever a ChildObject__c is created, I'd like to automatically create a new JunctionObect__c for each contact lookup field that is populated on ParentObject__c, and for each  related Contact I'd also like to create a new JunctionObject__c for that Contact's Account.

my code looks like this:

trigger createJuntion on ChidObject__c (after insert) {
    List<JunctionObject__c> insertList = new List<JunctionObject__c>();
   
    for(ChildObject__c co : Trigger.new){
        if (co.Contact__c != null ) {
            JunctionObject__c jo = new JunctionObject__c();
            jo.Contact__c = co.Contact__c;
            jo.Company__c = co.Contact__r.AccountID;

            insertList.add(rnContact);
        }
       insert inserList;
}


There are no errors thrown, but the Company field is not populated on the junction object.  I understand that I probably need to query the Contact's accountID through an alternative means, but would like some direction as to how.

Thanks!!!
Phillip SouthernPhillip Southern
Shayne,  you're correct...because you are essentially reaching up through the contact object to get a field on the account table..it won't be readily available on a trigger.  So what we need to do is query the data and add to a map to be referenced later....like this:

trigger createJuntion on ChidObject__c (after insert) {
    List<JunctionObject__c> insertList = new List<JunctionObject__c>();
    Set<Id> childobjectstoget = new set<id>();
    for(childObject__c c : trigger.new)
   {
             if(co.contact__c!=null)
            {
                  childobjectstoget.add(c.id);
             }
   }
   Map<Id,childobject__c> childobjects = new map<id,childobject__c>([select id, contact__c, contact__r.accountid from childobject__c]);
    for(ChildObject__c co : Trigger.new){
        if (co.Contact__c != null  && childobjects.containskey(co.Id) {
            JunctionObject__c jo = new JunctionObject__c();
            jo.Contact__c = co.Contact__c;
            jo.Company__c = childobjects.get(co.Id).Contact__r.AccountID;

            insertList.add(rnContact);
        }
       insert inserList;
}