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
Sammy ShkSammy Shk 

How to run Batch apex to update Records based on count

Hello, 

I'm new in apex and trying to run a batch apex. We have 2 objects, obj1 and obj2 and they have master detail relationship. We also have a End date time on obj1 and obj2 There could be multiple obj2 records related to obj1 , we want to run a batch that looks up all records in  Obj2 which has more than 2 records related to obj1 and update the old ones with the End date time field from obj1. Is there any sample code that I can start with?
CharuDuttCharuDutt
Hii Sammy
Try Below Code
public class testBatch implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT id,Name,End_date_time__c FROM obj1__c');
    }
    public void execute(Database.BatchableContext bc, List<obj1__c> records){
        ()
        set<Id> lstIds = new set<Id>();
        for(obj1__c led : records){
           lstIds.add(led.Id);
        }
        list<Obj2__c> ob2 = [select id,Name,CreatedDate,obj1__c from obj2__c where CreatedDate < Today And obj1__c In :lstIds];
        
        for(obj2__c obj2 : ob2){
            /*logic*/
        }
        if(ob2.size()>2){
        update ob2;
        }
    }
    public void finish(Database.BatchableContext bc){
        Id job = bc.getJobId();
    }
}
Please Mark It As Best Answer If It Helps
Thank You!

 
mukesh guptamukesh gupta
Hi Sammy,

First you need to create a RollUp summary with count method in Obj1__c, that will count total Obj2__c associated.

After that you can use below code, ion this code Total_Obj2__c(Rollup Summary field)  
 
global class BatchObj1Update implements Database.Batchable<sObject>,Database.Stateful {
    public integer count = 0;

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,Total_Obj2__c,End_date_time__c FROM obj1__c where Total_Obj2__c > 2';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<obj1__c> obj1List) {
         for(obj1__c obj1 : obj1List)
         {
             obj1.End_date_time__c = system.today();            
         }
       try{
      
        database.saveresult[] ds =  Database.update(obj1List,false);
            for(database.SaveResult d : ds){
                if(d.issuccess()){
                    count++;
                   system.debug('Batch Job'+ count +' : Ids of success records');

                }
                
            }
        }
        catch(exception e){
        system.debug('update failed');
        }
        
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 
Sammy ShkSammy Shk
@CharuDutt. Thanks!, I want to update all previous obj2 records with the End Date/time except the latest one. Do you know how do i update only the old ones but not the latest one ?
Sammy ShkSammy Shk
@MukeshGupta. Thank you, I don't see any obj2 records getting updated in the code you provided. Is there anything I'm missing?