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
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
Hemant_JainHemant_Jain
Please refer below link.

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

Hope this helps