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
Shank_dhelShank_dhel 

how to check the parent id of a child object on using schema

hi,

 

I am using schema to retrive all the objects

i need to check the records of the child object for  the  specific master object

 

 

its like i need to check

for (sobject Parent: parentrecordList) {

   for(sobject child :childrecordlist) {

      if(----) // need to frame a condition such that only the child record of the current parent record should go into the loop

   }

}

 

 

 

thanks in advance

 

d_hel

SFDCStarSFDCStar

Ex: X has related list A and B custom objects.

 

set<id> sId = new set<id>();
for(SobjectChild sc : Trigger.new){
sId.add(sc.A__c);
}


map<Id, X> parentMap = new map<Id, X>([Select Id from X where Id IN: sId]);

 

for (A obja : Trigger.new){
if (parentMap.containskey(obja.A__c)){
//Statements
}
}

ignatiuz_forceignatiuz_force

here is the best way to do it, example for account and opportunity objects

 

trigger accountTrigger on Account (before delete, before insert, before update) {
 
     //This code efficiently queries all related Closed Lost and
     //Closed Won opportunities in a single query.
    List<Account> accountWithOpptys = [select id, name, (select id, name, closedate,
         stagename  from Opportunities  where accountId IN&nbsp;:Trigger.newMap.keySet()
         and  (StageName='Closed - Lost' or StageName = 'Closed - Won'))
         from Account where Id IN&nbsp;:Trigger.newMap.keySet()];
    
    //Loop through Accounts only once
    for(Account a&nbsp;: accountWithOpptys){
        
         //Loop through related Opportunities only once
         for(Opportunity o: a.Opportunities){
             if(o.StageName == 'Closed - Won'){
                 System.debug('Opportunity Closed Won...do some more logic here...');
             }else if(o.StageName =='Closed - Lost'){
                 System.debug('Opportunity Closed Lost...do some more logic here...');
             }
         }
    
   }
}