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
Mak OneMak One 

Can we use related record in Trigger like currentObject__c.relatedObject__r.someField__c without querying

Suppose we have object ChildOfCase__c which has lookup to Case.
And an Object ToCreate__c have to get some values from case and then needs to be inserted after inserting any record in ChildOfCase__c.

So, can we do like: childOfCase.case__r.CaseSymptom1__c?
But when I am doing like this the records in ToCreate__c are not getting updated (just null values are there).

So, to get values from case then can we use

Below is the code in Trigger on ChildOfCase(after Insert):

List<ToCreate__c> rsList=new List<ToCreate__c>();
    for (ChildOfCase__c cr:Trigger.NEW) {
        if (cr.case__c!=null){
            ToCreate__c rs = new ToCreate__c(ChildOfCase__c=cr.id, Symptom1__c=cr.case__r.CaseSymptom1__c, Symptom2__c=cr.case__r.CaseSymptom2__c);
            rsList.add(rs);
        }
    }
   
    if (rsList.size()>0){
        insert rsList;
    }


Will it come in Trigger or we have to query separately for case?
Mak OneMak One
Fine!

Got answer here:

https://developer.salesforce.com/forums?id=906F000000090YSIAY

By sfck:
The data held in trigger.new (or trigger.old) does not include parent object data.

To access it you will need to get it out of the database yourself.

What I would do is get the set of IDs of the records that are being worked on by the trigger, and re-query them with the parent data attached.

1
set<id> triggerIds = trigger.new.keyset();
2
list<childObject__c> listWithParentData = [select Primary_Partner__r.Name, Primary_Partner__r.Address from childObject__c where id in :triggerIds];
Now you can work with listWithParentData as you would work with trigger.new.

----------------

So, I think we have to query only.
I also think of formula fields which can goto parent record and fetch value but read only. So, depends upon requirement.

Does anyone has any other inputs.
Tony TannousTony Tannous
Hello Mak,

as you said the only solution is to query the parent object fields in the trigger.

now  in case you are in a before insert trigger you can do the select statement on the parent object Ids, and put them in a Map,

map<Id,Case> mapCases=[// your select statement that contains a field from the parent ex :relatedObject__r.someField__c ]
and then 
for (ChildOfCase__c cr:Trigger.NEW)
{
        if (cr.case__c!=null && map.containskey(cr.case__c))
        { 
          // you can continue your logic here. 
         }
}


Regards