+ Start a Discussion
Sfdc CoupleSfdc Couple 

How to map from opportunity ids to the list of contact emails of all their associated accounts? Here Account is master and opportunity and conttact is child. So i want to query using opportunity.

My SOQL  query:


for(Account[] acc:[Select Id,name,(select Id,name from opportunities), (Select id, email from contact) from account ])


i want in apex. So kindly help me out here
Deepali KulshresthaDeepali Kulshrestha
Hi sfdc,

I've gone through your requirement and you can refer the below code that how to map opportunity corresponding to account and contacts:

List<Opportunity> allOpportunity=new List<Opportunity>([select id,Name,AccountId from Opportunity where AccountId!=null]);

Set<Id> accountIds=new Set<Id>();

for(Opportunity opp:allOpportunity)
{
accountIds.add(opp.AccountId);
}

List<Contact> allcontacts=new List<Contact>([select id,Name,AccountId from Contact where AccountId IN:accountIds);

Map<Id,List<Contact>> AccountVSContactMap=new Map<Id,List<Contact>>();
for(Contact con:allcontacts)
{

if(AccountVSContactMap.containsKey(con.AccountId)
{
AccountVSContactMap.get(con.AccountId).add(con);
}
else
{
AccountVSContactMap.put(con.AccountId,new List<Contact>());
AccountVSContactMap.get(con.AccountId).add(con);
}
}

Map<Id,List<Opportunity>> AccountVSOpportunityMap=new Map<Id,List<Opportunity>>();
for(Opportunity opp:allOpportunity)
{

if(AccountVSOpportunityMap.containsKey(opp.AccountId)
{
AccountVSOpportunityMap.get(opp.AccountId).add(opp);
}
else
{
AccountVSOpportunityMap.put(opp.AccountId,new List<Opportunity>());
AccountVSOpportunityMap.get(opp.AccountId).add(opp);
}
}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com