[SalesForce] How to add a lookup field value to an sObject list

Since I started coding in Apex, I've gotten used to working with lists of IDs of objects not the objects themselves.

This time around, instead of creating a List<ID> of account ids, I created a List<Account>.

Now, I'm trying to add account records to this list, via a lookup field on a related custom object. However, when I do this, I get an error back telling me I'm trying to add an ID to an sObject list.

So what I'm wondering is, how would I best indicate that it's the sObject record as a whole I want to add, not just the ID indicated by the lookup field? And if it involves a SOQL query, wouldn't that be problematic in terms of hitting governors limits?

Best Answer

Without sample code, it's hard to be certain, but I think you are saying you have something like this:

//You have a custom object, Widget__c, with a lookup to account
Widget__c widget = [select id, name, Account__c from Widget where id = :someId];

List<Account> accounts = new List<Account>();
accounts.add(widget.account__c);  // <-- error here, because account__c is an id

Instead of account__c, use account__r to refer to the object:

account.add(widget.account__r); // this works.

Note however that the account in the list will only have loaded the field values loaded in the original query. So if you will need the account.name (for example), add account__r.name to the query.

Also - the syntax is a little different for standard lookup fields. For example, if you were getting the Account from a Contact object, accountid refers to the id, but account refers to the object. This is consistent for all standard lookup fields that end with "id".