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
Murali Krishna 381Murali Krishna 381 

maps and soql

Create a Method to find for an Account what are its related case records
In terms of Hierarchy, An account can have mutliple contacts and one contact can have multiple cases
Create class and a method that queries all Accounts and prepare a map as below:
A map where key is the account Id and value is list of related Case Ids (Map<id,list<Id>> AccountRelatedCaseMap)
Note: Account is grand parent to case.   please help me in solving this use case guys
 
Arun Kumar 1141Arun Kumar 1141

Hi Murali Krishna,

I am sharing with you the apex class code for getting the Map of accountId Vs List<Case> Map 

public class AccountCaseController{
	public static Map<Id, List<Case>>  getMapOfCase(){
	
		List<Case> caseList =[SELECT Id, ContactId FROM Case];
		Set<Id> conIds = new Set<Id>();
		Map<Id, List<Case>> conIdVsCaseMap = new Map<Id, List<Case>>();
		for(Case c : caseList){
		 conIds.add(c.ContactId);
		 
		 if(!conIdVsCaseMap.containskey(c.ContactId) ){
			conIdVsCaseMap.put(c.ContactId, new List<Case>());
		 }
		 conIdVsCaseMap.get(c.ContactId).add(c);
		}
		
		
		List<Contact> conlist =[SELECT Id,AccountId FROM Contact WHERE Id IN : conIds];
		Set<Id> accIds = new Set<Id>();
		Map<Id, List<Contact>> accIdVsConMap = new Map<Id, List<Contact>>();
		for(Contact con : conlist){
		 accIds.add(con.AccountId);
		 
		 if(!accIdVsConMap.containskey(con.AccountId) ){
			accIdVsConMap.put(con.AccountId, new List<Case>());
		 }
		 accIdVsConMap.get(con.AccountId).add(con);
		}
		
		
		Map<Id, List<Case>> accIdVsCaseMap = new Map<Id, List<Case>>();
		for(Id accId : accIdVsConMap.keyset()){
		 for(Contact con : accIdVsConMap.get(accId)){
		 
		 if(!accIdVsCaseMap.containskey(accId) ){
			accIdVsConMap.put(accId, new List<Case>());
		 }
		 accIdVsConMap.get(accId).addAll(conIdVsCaseMap.get(con.Id));
		}
		
		return accIdVsConMap;
	}
}

If this answer is helpful to you then mark this as the best Answer.

Thanks