function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PRADEEP YADAV 5PRADEEP YADAV 5 

Account Related Opportunities Trigger . how to used only one single loop not a nested loop

trigger OpportunityOpen on Account(before delete)
{
    Map<Id, Account> mapacc = new Map<Id, Account>( [Select Id, Name, AnnualRevenue,
                            (Select AccountId, StageName From Opportunities)
                            From Account Where Id In : trigger.old]);
    for(Account a : trigger.old)
    {
        for(Opportunity opp : mapacc.get(a.Id).Opportunities)
        {
            if(opp.stageName=='closed won')
            {
                a.addError('associated open opportunities with account');
            }
        }
    }
}
Ankit Kalsara 6Ankit Kalsara 6
Hi Pradeep,

Can you please try below code. 
trigger OpportunityOpen on Account(before delete) {    
    
    // Get the related Closed Won opportunities for the accounts in this trigger
    Map<Id,Account> mapacc = new Map<Id,Account>(
                                      [SELECT Id,(SELECT Id FROM Opportunities WHERE StageName = 'Closed Won') FROM Account WHERE Id IN :Trigger.Old]);    
    
    // Iterate through each account.
    for(Account a : Trigger.old) {        
        // Check if the account already has Closed won Opportunity
        if (mapacc.get(a.Id).Opportunities.size() > 0) {
            // raise the error
            a.addError(''associated open opportunities with account');
        }           
    }    
}