
and I need to set account field with conatct field value but it is giving me an error
global final String Query = 'SELECT Contact.AAA__c ,Contact.Account.AAA__c FROM Contact';
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
list<Contact> conts = (contact[])scope;
for(Contact s : conts)
{
// here I am trying to set contact field value to account object but getting an error
s.Contact.Account.AAA__c = s.Contact.AAA__c; // getting error while saving file Invalid foreign key relationship Contact.Contact
}
8 respuestas
Hey Paddy,
Use this syntax instead - I made two changes:
1. I save the SOQL results in a variable so you can reference it multiple times
2. I "bulkified" your code because you'd run into errors if you tried the old code in a large operation
List<Contact> conts = (Contact[])scope;
System.debug('What are the contacts: '+conts);
// Get all the account ids and the contact's local account name in a map so we don't need to use a SOQL query for each contact
Map<Id, String> accountIdToContactAccountNameLocalMap = new Map<Id, String>();
for (Contact s : conts) {
accountIdToContactAccountNameLocalMap.put(s.AccountId, s.Account_Name_Local__c);
}
// Query and update all relevant accounts
List<Account> accts = [SELECT Id, Account_Name_Local__c FROM Account WHERE Id IN :accountIdToContactAccountNameLocalMap.keySet()];
for (Account a : accts) {
a.Account_Name_Local__c = accountIdToContactAccountNameLocalMap.get(a.Id);
}
// Now we can reference accts here
Database.SaveResult[] srList = Database.update(accts, false);
Hope this helps =)
David