You need to sign in to do that
Don't have an account?
Sviatlana 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.
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.
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
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.
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);
}
https://developer.salesforce.com/forums/?id=906F0000000913SIAQ
Hope this helps