Skip to main content

How to update only one latest child record's from list of Parent records ?

 This post is all about how to use aggregate query effectively or write less complex apex code.

Use Case: Lets say you need to update latest case record of each opportunity and  you have been given list of opportunity Ids. One opportunity can have multiple cases. How can you do it?

Approach - 1 If you are strong in SQL, you might be linking to use Group By Opportunity__c Order By CreatedDate Desc and Limit 1. SOQL does not support Order By limit along with Group By.

Approach - 2 Using Map to hold Opportunity Id with latest Case

Here is sample code 

// List of Opportunity IDs
List<Id> opportunityIds = new List<Id>{'oppId1', 'oppId2', 'oppId3'};

// Map to hold the latest Case for each Opportunity
Map<Id, Case> latestCaseMap = new Map<Id, Case>();
// Query all cases related to the Opportunity IDs,
sorted by CreatedDate descending to get the latest case first
List<Case> cases = [
    SELECT Id, Opportunity__c, Subject, Status, CreatedDate
    FROM Case
    WHERE Opportunity__c IN :opportunityIds
    ORDER BY CreatedDate DESC
];
// Loop through the cases and store the latest case for each Opportunity ID
for (Case c : cases) {
    Id oppId = c.Opportunity__c; // Assuming 'Opportunity__c'
is the lookup field on the Case object
   
    // If this Opportunity ID is not already in the map, add the current case
as the latest case
    if (!latestCaseMap.containsKey(oppId)) {
        latestCaseMap.put(oppId, c);
    }
    // Since the cases are already sorted by CreatedDate DESC, the first case
encountered is the latest one,
    // so no need to process further cases for the same Opportunity.
}

// Now latestCaseMap contains each Opportunity ID and its corresponding latest Case.
// You can iterate over it and perform the necessary update for each latest Case

List<Case> casesToUpdate = new List<Case>();
for (Id oppId : latestCaseMap.keySet()) {
    Case latestCase = latestCaseMap.get(oppId);    
    // Perform any necessary updates on the latest case
    latestCase.Status = 'Closed'; // Example: updating the status to 'Closed'
   
    // Add the case to the list for DML update
    casesToUpdate.add(latestCase);
}
// Update the latest cases for each Opportunity
if (!casesToUpdate.isEmpty()) {
    update casesToUpdate;
}
System.debug('Updated the latest case for each Opportunity.');

We can accomplish requirement in approach -2, but this is not efficient one.

Approach - 3 Using Aggregate Query.

Set<Id> caseIds = new Set<Id>();
List<Case> caseUpdateList = new List<Case>();
Case caseTemp;
// Query to get one Case ID per Approved_Lead__c (Opportunity)
List<AggregateResult> caseList = [
    SELECT Approved_Lead__c, Max(Id) caseId
    FROM Case
    WHERE Approved_Lead__c IN :oppyIds
    GROUP BY Approved_Lead__c
];

// Iterate through the results
for (AggregateResult ar : caseList) {
    Id opportunityId = (Id) ar.get('Approved_Lead__c'); // Opportunity ID (Approved_Lead__c)
    Id caseId = (Id) ar.get('caseId'); // The Case ID (MIN or MAX)
    caseIds.add(caseId);
    // Now you have the Opportunity ID and the Case ID
    System.debug('Opportunity ID: ' + opportunityId + ' Latest Case ID: ' + caseId);
}
for(Id cseId: caseIds){
caseTemp = new Case(Id=cseId, Status='Closed');
caseUpdateList.add(caseTemp);
}
If(!caseUpdateList.IsEmpty()){
    Update caseUpdateList;
}



  

Comments

Popular posts from this blog

Style in LWC

 Following are the ways we can apply in CSS in LWC. 1. Inline CCS Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div < template >     < lightning-card title = "Inline CSS" >         < div >             < div style = "color:green;font-size:10px;" > This is inline Style div </ div >         </ div >     </ lightning-card > </ template >  2. External CSS style can be applied to an elements such as h1, p,div span etc. It can applied to class using "." notation. for example .user{} It can also be applied to pseudo class.  for example .user:hover{} Id locator is not being used in LWC to apply style To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is ...

How to Create/Delete file attachments(Content Document) through Apex ?

 There are 3 standard salesforce objects to store file attachments. Content Document, ContentDocumentVersion, ContentDocumentLink.  Here is the article to talk about these objects and relationship.  https://www.forcetalks.com/blog/contentdocument-and-contentversion-in-salesforce-an-overview/ ContentDocumentVersion ContentDocumentLink This post is all about how to create/delete content document though Apex. Here is code snippet // Insert Content Version record ContentVersion contentVersionRec = new ContentVersion(Title='filename',PathOnClient ='FileName.pdf',VersionData = bodyBlob,origin = 'H'); INSERT contentVersionRec; // this will insert one record in ContentDocument and ContentVersion , ContentDocument  is parent and  ContentVersion is child record // get contentdocument id contentVersionRec = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionRec .Id LIMIT 1]; // Create Content Document Link record- This will attach ...

Lifecycle hooks in LWC

There are 3 phase of LWC component  1. Mounting  A. constructor, B. connnectedCallback C. render D. renderedCallback 2. UnMounting  A. disconnectedcallback 3. Error  A.errorcallback Note - render is not lifecycle hook, it is protected method of Lightning element class. Mounting Phase LWC Creation and Render Life cycle Constructor Method ·        This method called when component is instantiated and It flows from parent to child component. ·        Need to call Super() inside constructor method ·        Can’t access any component properties or child component because it’s not ready yet. ·        Host element can be accessed through “this. template” inside constructor method. ·        Don’t add any attributes to host inside constructor C   constructor (){          super (); //...