You need to sign in to do that
Don't have an account?
Mark Stoddard 17
How do I get all accounts related to a contact?
I have a List<Contact> in apex, but ultimately what I want is Map<Contact,List<String>> where the List<String> is the list of account numbers associated to the contact.
I had some working queries a while back, but I didn't think I'd need them, so got rid of them. Now I'm not sure how to do it. I assume I need to hit Account Contact Relationships somehow, but don't know how.
I had some working queries a while back, but I didn't think I'd need them, so got rid of them. Now I'm not sure how to do it. I assume I need to hit Account Contact Relationships somehow, but don't know how.
You need to use a subquery to grab the child accounts using the child relationship name.
It would look something like this:
Accounts__r is the child relationship name of the child accounts looking up to their parent contacts. You can find this by going to your account object and going to the detail page of the lookup field to contact.
Once you make the query you can put it in a map like this:
Hope this helps!
Sure, we can help but the question is not really clear:
are you using sharing contacts where one contact is related to multiple Accounts?
Map<Contact,List<String>>--- Here one contact will have multiple accounts
General use case would be as below:
Map<accountID,List<Contact>> accConMap--general map we hold account and related contacts data
List<Contact> conLst--You have this lIst ;
Map<ID,List<Contact>> accConMap--general usecase, we store account ID (may Key) and contacts data(Map values)
Set<ID> accSet= new Set<ID>();
For( Contact con: conLst)
{
if(con.accountID!=null)
{
accSet.add(con.accountID);
}
}
for (Account acc: [Select id,(Select id,accountID from Contacts) from Account where Id IN:accSet])
{
For(Contact con: acc.Contacts)
{
if(acc.Contacts.size()>0)
accConMap.put(acc.id,acc.Contacts)
}
}
Note : you may need to tweak a little bit since i just drafted it not checked for syntax errors.