If i have a query like

Map<Id,TER_Meter__c> mapIdToMeterPair=new Map<Id,TER_Meter__c>([Select Id,Name,(Select PAS_Customer_Consent_Flag_Effective_From__c,PAS_Customer_Consent_Flag_Effective_To__c,PAS_Consent__c from Consents__r),PAS_MSID_Effective_From__c,PAS_MSID_Effective_To__c,TER_Accepted__c from TER_Meter__c where Id in:meterIds]); 

Currently key part of map is id type and contains id of record being fetched, in this case TER_Meter__c.

  • Is there any way we can change what gets stored in the key part of the map while fetching value directly from query in to map.
  • If so is it also possible to store value from inner query to key part of map.

1 Answer 1


You can't change the key using Map constructor, it always uses the Id value. If you want to use any other key, you have to use a loop.

Map<Id, My_Object__c> records = new Map<Id, Object__c>();
for (My_Object__c record : [/*query*/])

If you want to pull a key from your inner join, then you need to consider the possibility there are no child records.

for (...)
    if (!record.Children__r.isEmpty())
        Child__c firstChild = record.Children__r[0];
        records.put(firstChild.Some_Field__c, record);
    // else?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .