Cascade Update in Salesforce

Cascade Update in Salesforce

Salesforce doesn’t implicitly updates the child record. So, we have to update the Child Records explicitly. Check the following code which makes use of updating both Parent And Child records in one DML Operation.

Sample code:
update new List < Account > (
    [ SELECT Id, (SELECT Id FROM Contacts ) FROM Account ]
);

The above code will not update the Contacts.

Sample Code to update Parent and child records at the same time:
List < sObject > listRecords = new List < sObject >();

for ( Account objAcc : [ SELECT Id, (SELECT Id FROM Contacts ) FROM Account LIMIT 5 ] ) {

    listRecords.add( objAcc );

    if ( objAcc.Contacts.size() > 0 ) {

        listRecords.addAll( objAcc.Contacts );

    }

}

update listRecords;

The above code does only one DML Operation.

Leave a Reply