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
RarLopzRarLopz 

Fetch related accounts for a contact

The salesforce org i am currently working on, instead of setting up many to many relationship between Account and Contact, they have multiple instances of the same contact, and each instance is related to unique account. 
E.g. In our org we have 200 Accounts for each of the 200 franchicess that do business with us. The person in charge (may be the area manager) for each of these stores is Sam Watkins. So in the org we have created Sam Watkins 200 times and related her to each of the Franchise. 
Sam Watkins  sam@email.com SW12  related to Account Acc001
Sam Watkins  sam@email.com SW12  related to Account Acc002
Where SW12 is the contacts unique identifier

In search if i type SW12, the list shows  all the 200 Accounst this person is related to.  

I have proposed to set up many to many relation between Account and Contacts so that we don't duplicate the same contact several hundered times, and also be able to build meaniful reports.  

My question is I want to fetch all instances of same Contacts that are associated with multiple accounts. 

This is how I can get one email at a time, but how can i get all contacts based on email addresses of all the Contacts who have multiple instances in the org.   
 
//retrieve related accounts for a contact
List<Contact> contactList = [Select id, name, AccountID
                       from contact where Email = 'sam@email.com'];

for(Contact con : contactList) {
    System.debug('Account id : ' + con.AccountID);
}

Thanks!
Egor Gerasimenko 9Egor Gerasimenko 9

I'm not really clear on what you are trying to get. Let's say in your org you have 3 contacts named Sam, 2 contacts named Bob, and 1 contact named Jim. What sort of a data structure are you trying to build in Apex? Are you trying to build a list of lists, with each inner list being all the duplicated contacts sharing the same email, like { { Sam, Sam, Sam}, {Bob, Bob}, {Jim} } ? You can't make a SOQL query for that, but it's easy enough to sort them in code

 

List<Contact> contacts = [SELECT Id, Name, AccountId, Email FROM Contact];
Map<String, List<Contact>> contactMap = new Map<String, List<Contact>>();
for (Contact con : contacts) {
    if (!contactMap.contains(con.Email)) {
        contactMap.put(con.Email, new List<Contact>());
    }
    contactMap.get(con.Email).add(con);
}

//print out the results
for (String email : contactMap.keyset()) {
    List<Contact> contacts = contactMap.get(email);
    System.debug('There are ' + contacts.size() + ' contacts for email ' + email);
    for (Contact con : contacts) {
        System.debug(con.Id);
    }
}

I typed that up right in the browser, so there might be typos and compile errors.