0

I have a soql with a subquery. What is the easiest way to pass the id of the query and the list of the subquery into a map.

Do I need to create a loop for the subquery and ad them first to the list?

Tried

 Map<id,List<edition__c>> bookMap = new Map<id,List<edition__c>>(); 
List<book__c> bookList = [select id, (select id,name from editions__r) from book__c];
for(book__c ti : bookList){
    bookMap.add(ti.id,ti.editions__r);  
}
system.debug('bookMap: ' + bookMap);
6

It should be bookMap.put instead of bookMap.add in your code. I don't see any other problem with your code.

0

Map keys are unique. So, if he adds multiple items with the same key, it will cause a problem. Try this code

List<Account> temp = new List<Account>([SELECT id,name from account]); 

Set<Id> accountIds = new Set<Id>();

for(Account acc:temp)
    accountIds.add(acc.Id);

List<opportunity> oppList= [select name,AccountId from opportunity where AccountId IN :accountIds];

Map<Id,List<Opportunity>> oppMap= new Map<Id,List<Opportunity>>();



for(Opportunity opp:oppList){  

    if(oppMap.containsKey(opp.AccountId)){
       List<opportunity> opp2= oppMap.get(opp.AccountId);
        opp2.add(opp);

        oppMap.put(opp.AccountId,opp2);

            }else{

            List<opportunity> opp1=     new List<opportunity>();
                opp1.add(opp);

                oppMap.put(opp.AccountId,opp1);

            }     

}


for(Id accId:oppMap.keySet()){

    system.debug('Account Id'+accId);

    system.debug('List of opportunities'+oppMap.get(accId));


}
2
  • I guess this would be you answer for another question? – Thomas Apr 18 '20 at 13:24
  • I just gave an example where an parent record can contain multiple child records in a format you wanted. Map<Id, List<childObjectRecords>> – Coding Artist Apr 18 '20 at 13:32
0

Just adding my 2 cents here, you could do it in a more elegant way:

Map<id, book__c> bookMap = new Map<id, book__c>(
    [select id, (select id, name from editions__r) from book__c]
); 

//now you have access to the children from the parent record and it's mapped to parent id
for(book__c book : bookMap.values()){
    System.debug(book.editions__r);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.