Search code examples
apexsoql

Running a query on a lookup table and returning the value in the private key


I have a trigger that is being tripped every time a Order is changed from draft to active and vise versa. I have a conditional inside my trigger that runs a query and saves the output into a Map. When I do a system debug on the Map the value being returned seems to be the foreign key.

trigger OrderActive on Order (after insert, after update){

for(Order ord : Trigger.New)
{
    If(ord.Status == 'Activated')
    {


                    Map<String, Order> m = new Map<String, Order>(
            [select Account.Name from Order WHERE Id IN :Trigger.new]);

        System.debug(m);

    }
}    

}

I keep getting the output in the image above

USER_DEBUG [12]|DEBUG|{8018A0000002fJYQAY=Order:{AccountId=0018A00000KvRm8QAF, Id=8018A0000002fJYQAY}}

When I run the same query in the Query Editor I get the actual name of the account instead of 0019A00000KvRm9QBF. How do I get my query in my trigger to pump out the name instead of the foreign key? Would a query in a trigger affect its, the query's, output?


Solution

  • Passing a query in a Map constructor will only ever use the Id as the map key, as you have stated:

    Map<String, Account> accountMap = new Map<String, Account>([Select Name From Account Limit 1]);
    System.debug(accountMap.keySet());
    

    Will produce this:

    15:48:48:011 USER_DEBUG [2]|DEBUG|{0012300000QaI0tAAF}
    

    You are going to have to manually fill the map with a custom values as the key:

    if(ord.Status == 'Activated') {
    
        Map<String, Order> m = new Map<String, Order>();
    
        for(Order o : [select Account.Name from Order WHERE Id IN :Trigger.new]) {
            m.put(o.Account.Name, o);
        }
    
        System.debug(m);
    
    }
    

    For example:

    Map<String, Account> accountMap = new Map<String, Account>();
    
    for(Account a : [Select Name From Account Limit 1]) {
        accountMap.put(a.Name, a);
    }
    
    System.debug(accountMap);
    

    will produce:

    15:53:56:034 USER_DEBUG [7]|DEBUG|{A-12910879=Account:{Name=A-12910879, Id=0012300000QaI0tAAF, RecordTypeId=012G0000000zoT7IAI, CurrencyIsoCode=USD}}
    

    Notice the "key" in the map is now the Account name as expected.