0

I have list values from child 1 from the below query child1list=[select name,id,parent__c,field11,field12 from child1__c]

I have list of child2 child2list=[select id,name,parent__r,parent__r.name,field21,field22 from child2 where parent__c in : parentids]

But I Have to update child1 fields in for loop as below accessing from child2 via parent

    for(child1__c child1 : child1list){
child1list.field11=child2list[].field21;//how to associate the related record here child2list[]
}

Can someone suggest me the approach? (I have child1 associated to parent1 which has only one child2)parent and child2 has master detail relationship too. parent and child lookup relationship. so here from child1 I have to get child2 record that which is associated to parent(one parent--one child2)

  • 2
    both child1 and child2 are children of 1 parent. So the relationship between child1 and child2 is many-to-many. How will you decide which child2 to pick in order to update the value on child1? – Guy Clairbois Oct 7 '16 at 18:39
  • But in my case the child1 associated to my parent has one child 2. Its a kind of one to one (ex: childrec1-- parentrec1---Child2) – Lalitha sfdc Oct 7 '16 at 18:43
  • 1
    do you mean the parent always has only 1 child2? And so child2list will always contain only 1 record? Or is this in a trigger and should it support bulk updates? – Guy Clairbois Oct 7 '16 at 18:44
  • the parent has only one child2 record(one parent-one child2). so here i have to access that child2 from child1. (one Parent - many child1). – Lalitha sfdc Oct 7 '16 at 18:47
1

As discussed, each parent has 1 child2 record (1:1 relationship). Each parent can have multiple child1 records.

In your query for child2 records you somehow need to 'remember' which child2 belongs to which parent, so you can later on match the correct child2 values to the child1 records (which have the same parent).

In order to do that, you will need to put the query results in a map, ordered by parentId:

Map<Id,Child2> parentIdToChild2Record = new Map<Id,Child2>();
for(child2 c2 : [select id,name,parent__r,parent__r.name,field21,field22 from child2 where parent__c in : parentids]){
   // since we know that each parent will only have 1 child2, there is no need to verify if the map already contains a value for that parentId
   parentIdToChild2Record.put(c2.parent__c,c2);
}

Now we have the map ready for fetching the values that we need to put in child1:

for(child1__c child1 : child1list){
   child1list.field11 = parentIdToChild2Record.get(child1.parent__c).field21;
}

Getting to understand and use maps is a vital skill for programming in APEX. So make sure you do some Trailhead training on this.

  • -Used the same its working fine thank you – Lalitha sfdc Oct 8 '16 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.