Update a field in c...
 
Notifications
Clear all

[Solved] Update a field in child records from the fields value in parent

2 Posts
1 Users
0 Likes
323 Views
Posts: 205
 CWL
Admin
Issue starter
(@cwl)
Member
Joined: 11 years ago

How to update a field on all records in a child record collection with a fields value in its parent.

Issue Tags
1 Reply
Posts: 205
 CWL
Admin
Issue starter
(@cwl)
Member
Joined: 11 years ago

This is to update a child object field (downloads__c) in each of the child records in the child object (Data__c) record collection, with the value of a field (downloads__c) from its parent object (Parent__c). The parent object also has the field count__c:

// child records to be updated received from json
jsonBody = '[{"count__c":"445", "downloads__c":"340"}, {"count__c":"440", "downloads__c":"240"}]';

List dList = (List) System.JSON.deserialize(jsonBody, List.class);

countList has unique count__c values, say: 445,440 // to use in the IN clause.

// Querry parent for those plan ids in daily data json
List parentList = [SELECT Id, Name FROM Parent__c 
    WHERE count__c IN :countList];

List dataToInsert = new List();

// Loop through dList - inner loop
for(Data__c dRecords : dList) {
     for(Parent__c parentRecords : parentList) {         
          if(dRecords.count__c  == parentRecords.count__c) {
                dRecords.downloads__c  = parentRecords.downloads__c ;
                dataToInsert.add(dRecords );
           }
      } 
} 
insert dataToInsert;

 

Reply
Share: