I have a batch process to update Accounts with address info from the Cust_Address__c object. I use a Junc_Account_Address__c object as a junction. How do I loop through the accounts to update the addresses. Currently I get the error Loop must iterate over collection:Account
global class AddressManager implements
Database.Batchable<sObject>, Database.Stateful {
// instance member to retain state across transactions
global Integer recordsProcessed = 0;
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Start_Date__c, End_Date__c, Account__c, Cust_Address__c, Recordtype' +
'FROM Junc_Account_Address__c' +
'WHERE Start_Date__c <= TODAY AND End_Date__c >= TODAY'
);
}
global void execute(Database.BatchableContext bc, List<Junc_Account_Address__c> scope){
// process each batch of records
List<Account> accountsToUpdate = new List<Account>();
for (Junc_Account_Address__c ac : scope) {
for (Account acc : ac.Account__r) {
acc.BillingStreet = ac.Cust_Address__r.BillingStreet__c;
acc.BillingPostalCode = ac.Cust_Address__r.BillingPostalCode__c;
acc.BillingCity = ac.Cust_Address__r.BillingCity__c;
acc.BillingState = ac.Cust_Address__r.BillingState__c;
// add account to list to be updated
accountsToUpdate.add(acc);
// increment the instance member counter
recordsProcessed = recordsProcessed + 1;
}
}
update accountsToUpdate;
}
global void finish(Database.BatchableContext bc){
System.debug(recordsProcessed + ' records processed. Shazam!');
AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,
JobItemsProcessed,
TotalJobItems, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :bc.getJobId()];
// call some utility
}
}
Junc_Account_Address__c
or it can be multiple? – rahul gawale Dec 12 '19 at 11:14Junc_Account_Address__c
,ac.Account__r
is not a list but a single record which you will never get in your query as you are not querying any field from an account object. And for loop work on collections only not a single record. see the linefor (Account acc : ac.Account__r) {
– rahul gawale Dec 12 '19 at 11:16