I've got a scenario where a status field on the parent object needs to be updated to reflect the status of the most recently created child object. To solve this, I've done a SOQL with a subquery :-

Select Id, CRA_Status__c, (Select Id, Status__c, CreatedDate from CRAs__r order by CreatedDate DESC LIMIT 1) from Client__c

but what is the correct combination of Collection classes to house it? I suspect a list of wrapper classes is the only way, but happy to get suggestions from people

  • 1
    What are you trying to achieve? You don't necessarily need any classes at all, but it is impossible to make a recommendation without placing your requirements in context. Are you trying to display these values in Visualforce? Update them in a batch/trigger? – Adrian Larson Jun 29 '17 at 10:30
  • Yes, it's a trigger update - when the status on the child changes, verify if it's the most recently created child and ensure the parent reflects the status to match – Rob Cowell Jun 29 '17 at 10:32

You don't need any helper classes at all. You can just iterate through the results and update the parents accordingly. In this case the "correct" structure is the one you find easiest to write and test. But it doesn't have to be any more complicated than the below:

List<Parent__c> toUpdate = new List<Parent__c>();
for (Parent__c parent : [
        CRA_Status__c, (
            SELECT Status__c, CreatedDate FROM Children__r
            ORDER BY CreatedDate DESC LIMIT 1
    FROM Parent__c WHERE ...
    if (!parent.Children__r.isEmpty() && parent.CRA_Status__c != children[0].Status__c)
        toUpdate.add(new Parent__c(CRA_Status__c=children[0].Status__c));
update toUpdate;
  • At first I thought that was SOQL in a for loop, but it's just StackExchange code formatting. That's nice and elegant - it still treats it a simple list of the parent object, no list-of-lists to worry about. – Rob Cowell Jun 29 '17 at 10:44

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.