i want to create a map<Id, List<Contact> >, Where ID means AccountID and List<Contact> are Child Record If there is 4 child rec of 1 parent so i want id of parent as key and value as child rec
Map<Id, List<Contact>> accountToContactsMap = new Map<Id, List<Contact>>();
// Query for the parent Account and its related child Contacts
List<Account> parentAccounts = [SELECT Id, (SELECT Id FROM Contacts) FROM Account];
// Loop through the parent Accounts and their child Contacts to populate the map
for(Account account : parentAccounts) {
List<Contact> contacts = account.Contacts;
if(contacts != null && !contacts.isEmpty()) {
accountToContactsMap.put(account.Id, contacts);
}
}
This code first queries for the parent Accounts and their related child Contacts using a subquery. It then loops through the parent Accounts and their child Contacts, populating the map with the Account Id as the key and the list of Contacts as the value.
If this information helps, please mark the answer as best. Thank you
Try
This code first queries for the parent Accounts and their related child Contacts using a subquery. It then loops through the parent Accounts and their child Contacts, populating the map with the Account Id as the key and the list of Contacts as the value.
If this information helps, please mark the answer as best. Thank you