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
SalesForce DummySalesForce Dummy 

Pull data from a map

I've created a map but am having a hard time figuring out how to pull data from it. Here's the map: Map m = new Map([SELECT ID, (SELECT ID FROM Contacts) FROM Account LIMIT 5]); How do I get to the fields from the Contact table?
sfdcfoxsfdcfox

You reference Contacts as an array. Here's an example:

 

 

Map<Id,Account> accounts = new Map<Id,Account>([select id,(select id from contacts) from account limit 5]);
for(Account a:accounts.values()) {
  System.Debug('*** Account: ' + String.valueOf(a.id));
   for(Contact c:a.Contacts) {
      System.Debug('*** Contact: ' + String.valueOf(c.id));
   }
}

Of course, you can also do things like:

 

 

 

// Iterate through all contacts in a specific account
for(Contact c:accounts.get(someAccountId).Contacts)
{ ... }

 

 

Note that this is a List<Sobject>, not Map<Id,Sobject>, so if you need that sort of mapping, you would have to do something like this:

 

 

Map<Id,Map<Id,Contact>> accountContacts = new Map<Id,Map<Id,Contact>>();
for(Account a:[select id,(select id from contacts) from account limit 5])
{
  accountContacts.put(a.id, new map<id,contact>(a.contacts));
}