+ Start a Discussion
Sviatlana AndryianchykSviatlana Andryianchyk 

Create Map from junction table

Hi
I am using two kind of objects: Item and Category. They are linked via junction table CategoryItem. So, how to select objects into Map<Category, Item[]>. This map should contain array of items under each category. Thank you in advance.
Best Answer chosen by Sviatlana Andryianchyk
Neha LundNeha Lund
Map<Id,List<Item>> categoryItemsMap = new Map<Id, List<Item>>();
List<Item__c> itemList = new List<Item__c>();

for(Item__c item: [SELECT id, Category__c from Item__c ]){
 
  if(categoryItemsMap.containsKey(item.Category__c))   
  itemList = categoryItemsMap.get(item.Category__c);
   
  itemList.add(item);
 categoryItemsMap.put(item.Category__c, itemList);

}

All Answers

Neha LundNeha Lund
Hello,

Please query all the items in the for loop and based on the key i.e Category, keep adding the items in the list.

Thank you.
Neha LundNeha Lund
Map<Id,List<Item>> categoryItemsMap = new Map<Id, List<Item>>();
List<Item__c> itemList = new List<Item__c>();

for(Item__c item: [SELECT id, Category__c from Item__c ]){
 
  if(categoryItemsMap.containsKey(item.Category__c))   
  itemList = categoryItemsMap.get(item.Category__c);
   
  itemList.add(item);
 categoryItemsMap.put(item.Category__c, itemList);

}
This was selected as the best answer
HemantJain0206HemantJain0206
Please refer below link.

https://developer.salesforce.com/forums/?id=906F0000000913SIAQ

Hope this helps