You need to sign in to do that
Don't have an account?
AlSawtooth
How can I bulkify this code? (SOQL inside for loop)
I'm trying to count the total number of distinct years for which a given account has associated opportunities. This code works fine in individual cases, but breaks during bulk updates. Any ideas?
trigger UpdateOppYears on Opportunity (after update, after insert, after delete) { if(Trigger.IsUpdate || Trigger.IsInsert){ List<Account> accs = [SELECT Id, Years_of_Opps__c FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity WHERE Id in:Trigger.newMap.keySet() AND AccountId != null AND StageName = 'Received')]; for(Account a: accs) { AggregateResult[] groupedResult = [SELECT AccountId, COUNT_DISTINCT(CloseYear__c) NumberOfDistinctYears FROM Opportunity o WHERE AccountId = :a.Id AND o.StageName = 'Received' GROUP BY AccountId]; Decimal aggregateCount = (Decimal)groupedResult[0].get('NumberOfDistinctYears'); a.Years_of_Opps__c = aggregateCount; } update accs;
^ - Needs a bit of work, but thats generally how you would bulkify.
All Answers
^ - Needs a bit of work, but thats generally how you would bulkify.
And thank you so much for your help!!
I'm getting an error that says Compile Error: Invalid initial expression type for field Account.Id, expecting: Id at line 18 column 42. If I add a ".Id" at the end (like below):
I'm getting an Compile Error: Initial term of field expression must be a concrete SObject: Object at line 18 column 57 error.
Do you know what I should do here?
get('field') returns a generic object. You'll need to cast the aggregated fields to their respective types of Id and either Decimal or Integer. For instance: