+ Start a Discussion
Randy RoseRandy Rose 

batch job update object using id from another object

Due to hitting CPU Limit, I need to update my batch job.  I thought this would be simple but can't figure how to move an Object and assoicated field (total amount) to a collection; meaning I have access to the Object ID (Opportunit) from another Object (Payment) but don't know how to move this to a collection


The job does the following
  1. Retrive all payment records (status = 'completed'); approx. 20,000 payment records!
  2. Batch Job (processes 100 payments per job <List>Payments)
(a) Create List of Opportunity (status = 'closed won')
(b) iterates through payment records
(c)  for each payment record find matching opportunity (2,500 opporunities; this technically loops 250,000 times - 100 payments X 2,500 opportunites)
(d) add payment amount to Opportunity.payment_amt
(e) when payment loop is complete 'update Opporunity' (list from (a) )

Its seems obvious that the loop is causing the CPU Limit (although, this error is random). What I've decided to do is modify the Payment collection List and order by Opportunity id -> Opp_id, payment_amt, pament_date.

So instead of trying to find matching Opportunity (on Opporunity object), I can just total the amount until the Opportunity ID is differnet from the next record in the payment List.
  1. Retrive all payment records and order by Opporunity Id (this is on Payment object0
  2. Batch Job (processes 100 payments per job <List>Payments)
(a) iterates through payment records (List)
(b) add payment amount to Opportunity.payment_amt
(c) when Opportunity changes, add total amount to a List
(e) when loop is complete 'update Opporunity'

So now I have Opportunities what their totaly amounts. 

How do I add these amounts to a list (or map) so I can do a 'bulk' update?