I am upserting a custom object record and I want to populate a lookup field. My thinking is that I need to do a query in the for loop get the id then push that to an id variable (externalid). Then finally when I go to upsert just say lookup__c = external id

The object in the lookup has an external id, can I just search on that in the upsert call?

If not, I wrote this bit of code to get the id and then pass it through if there is a result. When I try to compile I get:

Initial term of field expression must be a concrete SObject ListProduct_Structure__c

How can I get this lookup populated the most efficiently?

List<Product_Structure__c> prodStructure = [SELECT Id 
                                            FROM Product_Structure__c
                                            WHERE External_Id__c = :field__c LIMIT 1];
            prodStructure != null){

A List<SObject> does not have an Id property. You can get the first record from the list instead, in this case.

List<MyObject__c> records = [/*query*/];
if (!records.isEmpty())
    Id recordId = records[0].Id;
    // further processing

If you want to figure out how to upsert relationships based on an external id, take a look at Set Relationship Via Name Pointing Field? You actually don't even need to upsert. The basic idea is that if you know the external id of the parent, you can do:

MyObject__c record = new MyObject__c();
record.Parent__r = new Parent__c(External__c = '<external_id>');
insert record;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.