Suppose i have 3 related objects: Continent - Country - City. Country object is child object of Continent and City is child object of Country. City -> Country -> Continent.
I would like make changes to a field on the continent object, based on a field on the city object. I want to use Batch Apex for this approach. So e.g. Say City has a field called ''Population''. If population on any city in any Country for a given Continent is more than 50.000.000, then a checkbox (Potential Customers) on Continent should change. But if the Continent does not have any Country with any City more than 50.000.000, then the checkbox should be/remain unchecked.
So, I understand that for this approach I cannot query downwards, going from parent to child object since we are going more than 1 level deep, hence it is necessary to query upwards, from child to parent. I imagine the query something like this:
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Name, Population__c, Country__r.Id, Country__r.Continent__r.Id, Country__r.Continent.Potential_Customers__c FROM City__c]);
}
The execute method gives me trouble. I do not know how this should be done or how it can be done the smartest way. I am still learning Apex and SOQL. My suggestion would be using inner loops,
For(Continent)
For(Country)
For(City)
if(Population > 5.000.000)
Potential_Continent__c = true
But again, I am not sure how i can do this programtically. And there are probably smarter ways to accomplish my problem above. Can anyone help?