+ Start a Discussion

How to update a field in Apex from a Relationship Query

I have a Query like this ...



for(opportunity opp1 :opp){

ProcessInstance p= [SELECT Id, (SELECT Id, StepStatus,Comments FROM Steps)FROM ProcessInstance  WHERE Status='Approved' and  TargetObjectId=:opp1.id limit 1];


opp1.comments = p.comments; 


//This is not working


i want to get the comments from the Query to custom field




any ideas please!!

Ritesh AswaneyRitesh Aswaney

It should be


opp1.comments = p.Steps__r[0].comments; 


Steps__r is the relationship name, this could be different depending on what you've set it to


And ideally, that SOQL Query should not be inside the FOR loop. Aggregate criteria inside the for loop and query once aggregated. just best practice.

Ankit AroraAnkit Arora

Have you tried this ???


p.steps[0].comments instead of p.comments



Ankit Arora


Ankit AroraAnkit Arora

(SELECT Id, StepStatus,Comments FROM Steps) will return you the list of all steps related. You can fetch them by there index.



Ankit Arora



Thank you..


I used This


ProcessInstance p= [SELECT Id,Status FROM ProcessInstance  WHERE Status='Approved' and  TargetObjectId=:opp1.id limit 1];
ProcessInstancestep sp =[select id,comments from ProcessInstancestep where ProcessInstanceid =:p.id limit 1];