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
Kiril Vodenicharov 7Kiril Vodenicharov 7 

How to use Map collection to associate between Account and Opportunity

How to write a trigger that creates 10 identical Opportunities whenever an Account with more than 99 employees is created. Make sure all Opportunities are associated with the Account. Use any values for the fields on the Opportunities and to work with Map collection.
Suraj Tripathi 47Suraj Tripathi 47
Hi Kiril Vodenicharov 7, 
Kindly find solution.
 
// class
public class RealatedAccountAndOpportunity {
    public static void relateAccountWithOpportunity(){
       
        List<Opportunity> opportunityList = new List<Opportunity>([select id ,AccountId from Opportunity where AccountId != null]);
        Map<Id, List<Opportunity>> accountId_Vs_ListOfOpportunity = new Map<Id, List<Opportunity>>();
        
        for(Opportunity opp : opportunityList){
            if( !accountId_Vs_ListOfOpportunity.containsKey(opp.AccountId)){
                List<Opportunity> oppList = new List<Opportunity>();
                oppList.add(opp);
                accountId_Vs_ListOfOpportunity.put(opp.AccountId, oppList);
                
            }
            else{
                List<Opportunity> oppList = new List<Opportunity>();
                oppList = accountId_Vs_ListOfOpportunity.get(opp.AccountId);
                oppList.add(opp);
                accountId_Vs_ListOfOpportunity.put(opp.AccountId, oppList);
            }
        }
        //By using this accountId_Vs_ListOfOpportunity , You can relate account and Opportunity.
    }

}
If you find your Solution than mark as this as a best answer. 

Thanks and Regards
Suraj Tripathi.
Kiril Vodenicharov 7Kiril Vodenicharov 7

Okay, but when you create account the Opportunity creation must be based on Account employees. If the account employees are 99 then you have to create 10 identical Opportunities.

 

Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Name FROM Account WHERE Id IN: accList AND NumberOfEmployees > 99]);       
        List<Opportunity> oppList = new List<Opportunity>();
        
        for(Integer i = 0; i < 10; i++) {
            for(Account acc : [SELECT Id, Name FROM Account WHERE Id IN: accountMap.keySet()]) {
                    Opportunity opp = new Opportunity();
                    opp.AccountId = acc.Id;
                    opp.Name = acc.Name;
                    opp.CloseDate = Date.today();
                    opp.StageName = 'Prospecting'; 
                    oppList.add(opp);
                }
        }    
        
        insert oppList; 


Something like this one that I've written, but without nested loops.