I have three objects, namely Tests, Grant, and Grant Contracts.
Here in Tests
object I have given a lookup to Grant
and Grant Contract
. I have also given a lookup in Grant Contract
to the Grant
object. In the lookup fields in all the test records, I have the grant record id.
My aim is to update all the grant contract fields in the test records, and these grant contracts should be of the parent grant object. So if I have a Tests record with Grant G and Grant Contract GC, I should get the tests record's grant contract field filled with the GC child record present in the Grant G.
I am planning to use anonymous code for updating as there is a bulk amount of records. Please provide an input on how to start. I have started this way.
List<Test__c> TestList =[Select id,name,Grant__c from Test__c where Grant__c!= null];
System.debug('Test==>'+TestList);
System.debug('TestList==>'+TestList.size());
Set<Id> grantId = new set<Id>();
Set<Id> grantContractId = new set<Id>();
For(Test__c t :TestList) {
grantId.add(t.Grant__c);
}
System.debug('grantId==>'+grantId);
System.debug('grantId Set==>'+grantId.size());
***Modified code and debug logs after the valuable answers from the comments.***
List<Test__c> TestList =[Select id,name,Grant__c,Grant_Contract__c from Test__c where Grant__c!= null];
System.debug('Test==>'+TestList);
System.debug('TestList==>'+TestList.size());
Map<Id, Grant_Contract__c> grantContractRecordsById = new Map<Id, Grant_Contract__c>();
System.debug('grantContractRecordsById');
for(Test__c record: [
SELECT Grant__c,Grant_Contract__c
FROM Test__c
WHERE Grant__c!=null AND Grant_Contract__r.Grant_Name__c=null
LIMIT 10000])
System.debug('record>=='+record);
{
grantContractRecordsById.put(
record.Grant_Contract__c,
new Grant_Contract__c(
Id=record.Grant_Contract__c,
Grant_Name__c=record.Grant__c
)
);
}
update grantContractRecordsById.values();