+ Start a Discussion
❤Code❤Code 

query related list and update parent record

Hi All,

I have an Object X__c which is having related list R__c. R__c has two fields F1, F2. I need to query these fields and update the field values in X__c s1, s2 field.

Need help.

Regards
Suresh RaghuramSuresh Raghuram
In dev console write the following lines of code

List<X__c>  xList = [Select id, (select F1,F2 from R__r) from X__c];
(make sure your child relationship object API name is as I said R__r or not( because this name is taken by salesforce itself internally
suppose some times if you give book__c as object name and expect the book__r will be child relationship object name, but it may take as books__r.)
List<X__c> updatedList = new List<UpdatedList>();
for(X__c x:xList){
    if(x.R__r.F1 != null){
            x.s1 = F1;
    }
    if(x.R__r.F2 != null){
             x.s2 = F2;
    }
updatedList.add(x);
}
update updatedList;

Just modifiy a little to place the same into  the trigger if you want and need any help I am happy to help you.
If this answers your question make this as a solution.
❤Code❤Code
Hi Suree,

Thanks for the help. I am trying to do the below operation but its not working . 
trigger rollupTolltoPhase on Toll_Gate__c (after insert, after delete,after undelete,after update) {

    Set<Id> pId = new Set<Id>();
      
    if(Trigger.isInsert){
    for(Toll_Gate__c tpp : Trigger.New){
    pId.add(tpp.Project_Phase__c);
    }
    
    List<Project_Phase__c> pp = [SELECT id,Toll_Gate__r.Sum_Of_Task_Bill_Days__c  FROM Project_Phase__c where Id =:pId];
    List<Project_Phase__c> ppc = new List<Project_Phase__c>();
 
  //  List<Toll_Gate__c> tol = [select id,Sum_Of_Task_Bill_Days__c from Toll_Gate__c where Project_Phase__c in :pId];
   // system.debug('@@@ tol' + tol);
    
    For(Project_Phase__c p: pp){
    if(p.Toll_Gate__r.Total_Task__c!=null){
    
    p.Sum_Of_Task_Bill_Days__c  = p.Sum_Of_Task_Bill_Days__c + p.Toll_Gate__r.Sum_Of_Task_Bill_Days__c;
    
     }
    ppc.add(p);
    }
    update ppc;
    }
    
   
}

Can u tell whts going wrong.
 
Suresh RaghuramSuresh Raghuram

List<Project_Phase__c> pp = [SELECT id,Toll_Gate__r.Sum_Of_Task_Bill_Days__c  FROM Project_Phase__c where Id IN:pId];

If you are encountering any errors, post that too so that I can understand what went wrong quickly.
❤Code❤Code
Hi Suree, 

I need to fetch the Toll_Gate__r.Sum_Of_Task_Bill_Days__c value and update it Project_Phase__c field. How can i do that.

Regards