Search code examples
foreign-keysparent-childprimary-keyapexsoql

Fetching user freindly values from a lookup field


I am trying to write a query in my apex trigger that will return a user friendly value.

Map<String, Order> order_1 = new Map<String, Order>([
Select Account.Name
From Order
]);

System.debug('Order 1: ' + order_1);

When I write the query in my trigger it returns some odd number letter combinations but when I write it in the query editor it returns something like "Toys R Us" for instance. Why does the query return the foreign key instead of the data when in my trigger but returns the actual account name in the query editor?


Solution

  • This is because passing a query into the Map constructor will use the record Id as the key. I think what your after is this:

    Map<String, Order> order_1 = new Map<String, Order>();
    
    for(Order o : [Select Account.Name From Order]) {
        order_1.put(o.Account.Name, o);
    }
    
    System.debug('Order 1: ' + order_1);