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
Jason VoightJason Voight 

Create a Map from parent to grandchild

Hello I was wondering what was the best way to create a map of 3 related objects. Eg. The grandchild looks up to the child, the child looks up to the parent. I know that you can use dot notation to get to the Parent from the grandchild, but was needing to go from the Top down. Would like to associate a key pair if possible
Best Answer chosen by Jason Voight
Shri RajShri Raj
a nested forloop can help you in my opinion. 
Map<Id, List<GrandChild__c>> parentToGrandChildMap = new Map<Id, List<GrandChild__c>>();

for (Parent__c parent : [SELECT Id, (SELECT Id, Name FROM Children__r) FROM Parent__c]) {
    List<GrandChild__c> grandChildList = new List<GrandChild__c>();
    for (Child__c child : parent.Children__r) {
        for (GrandChild__c grandChild : [SELECT Id, Name FROM GrandChild__c WHERE Child__c = :child.Id]) {
            grandChildList.add(grandChild);
        }
    }
    parentToGrandChildMap.put(parent.Id, grandChildList);
}

 

All Answers

Shri RajShri Raj
a nested forloop can help you in my opinion. 
Map<Id, List<GrandChild__c>> parentToGrandChildMap = new Map<Id, List<GrandChild__c>>();

for (Parent__c parent : [SELECT Id, (SELECT Id, Name FROM Children__r) FROM Parent__c]) {
    List<GrandChild__c> grandChildList = new List<GrandChild__c>();
    for (Child__c child : parent.Children__r) {
        for (GrandChild__c grandChild : [SELECT Id, Name FROM GrandChild__c WHERE Child__c = :child.Id]) {
            grandChildList.add(grandChild);
        }
    }
    parentToGrandChildMap.put(parent.Id, grandChildList);
}

 
This was selected as the best answer
por gelpor gel
The great features of epayitonline are that you don't have to provide any personal information or create an account to pay health bills online. https://peryourhealth.ninja/features-of-epayitonline/