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
ColbridgeColbridge 

Update a child record field with a value of a field of its corresponding parent

What I am trying to do 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.
 
Once all the records are updated in the child collection, do a dml insert after the loop. Can't seem to get this to work. Hope I have explained correctly.
 
jsonBody = '[{"count__c":"45","downloads__c":"30"},{"count__c":"40","downloads__c":"20"}]'; // child records to be updated

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

countList has unique count__c values, say 45,40 // to use in the IN clause.

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

// Loop through the list of returned parent records - outer loop
for(Parent__c parentRecords : parentList) {
    // Loop through dList - inner loop
    for(Data__c dRecords : dList) {
        // look for matching count__c in parent 
        // update corresponding downloads__c in the child record with its parents downloads__c value
    } 
} 

Should I use maps, if so how?

// dml insert of child collection

 
Best Answer chosen by Colbridge
AnkaiahAnkaiah (Salesforce Developers) 
Hi colbridge,

Use the below code.
// Querry parent for those plan ids in daily data json
List<Parent__c> parentList = [SELECT Id, Name,downloads__c  FROM Parent__c 
    WHERE count__c IN :countList];

List<Data__c > datatoupdate = new List<Data__c >();

    // Loop through dList - inner loop
    for(Data__c dRecords : dList) {
        for(Parent__c parentRecords : parentList) {
dRecords.downloads__c  = parentRecords.downloads__c ;
datatoupdate.add(dRecords );
    } 
} 
update  datatoupdate;


 

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi colbridge,

Use the below code.
// Querry parent for those plan ids in daily data json
List<Parent__c> parentList = [SELECT Id, Name,downloads__c  FROM Parent__c 
    WHERE count__c IN :countList];

List<Data__c > datatoupdate = new List<Data__c >();

    // Loop through dList - inner loop
    for(Data__c dRecords : dList) {
        for(Parent__c parentRecords : parentList) {
dRecords.downloads__c  = parentRecords.downloads__c ;
datatoupdate.add(dRecords );
    } 
} 
update  datatoupdate;


 
This was selected as the best answer
ColbridgeColbridge
Thanks Ankaiah! That was it. I placed the two lines of field updatiion and adding to the list to update in an if condition as well to update only the matching count__c fields in both objects.