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
Mark Stoddard 17Mark 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.
UC InnovationUC Innovation
Hi Mark,

You need to use a subquery to grab the child accounts using the child relationship name.

It would look something like this:
 
[SELECT ID, Name, (SELECT ID, AccountNumber FROM Accounts__r) FROM Contact];
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:
 
Map<Contact, List<String>> mapOfContactAndChildAccountNums = new Map<Contact, List<string>>();

for (Contact c: queryResult)
{
    mapOfContactAndChildAccountNums.put(c, new List<string>);
    for (Account a: c.Accounts__r)
    {
         mapOfContactAndChildAccountNums[c].add(a.AccountNumber);
    }
}

Hope this helps!
Prasad Avala(SFDC-SF)Prasad Avala(SFDC-SF)
Hi Mark,
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.