I'm still very much new to Apex so I was hoping to get some feedback on a trigger I wrote. The requirement is upon an opportunity reaching stage 5, query the account team of the related Account and find the relationship and technical account manager and write that to the opportunity.
The code works but I'm wondering if I should only use one query. What can I do to optimize this? Thanks in advance
trigger Opportunity_SetAcccountTeamOnClose on Opportunity (before update) {
set<ID> AccountIDs = new set<ID>();
map<ID,AccountTeamMember> RMTeamMap=new Map<ID,AccountTeamMember>();
map<ID,AccountTeamMember> TAMTeamMap=new Map<ID,AccountTeamMember>();
for(Opportunity o : Trigger.new){
if(o.StageName == 'Stage 5'){
AccountIDs.add(o.accountid);
}
}
for(AccountTeamMember rmatm : [Select a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
From AccountTeamMember a
where a.TeamMemberRole='Relationship Manager' AND a.AccountId in :AccountIDs]){
RMTeamMap.put(rmatm.Accountid,rmatm);
}
for(AccountTeamMember tamatm : [Select a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
From AccountTeamMember a
where a.TeamMemberRole='Technical Account Manager' AND a.AccountId in :AccountIDs]){
TAMTeamMap.put(tamatm.Accountid,tamatm);
}
for(Opportunity o : Trigger.new){
if(o.StageName == 'Stage 5'){
if(RMTeamMap.containsKey(o.AccountId)){
o.Relationship_Manager__c=RMTeamMap.get(o.AccountId).User.Name;
if(TAMTeamMap.containsKey(o.AccountId)){
o.Technical_Account_Manager__c=TAMTeamMap.get(o.AccountId).User.Name;
}
}
}
}
}