I am creating a service record when opportunity is closed won and product code in opportunity line item is null. I am filling the new service record with the values from opportunity line item and opportunity, now they want data from account object, please help me to figure out this When i uncomment the Account Acc....i get invalid foreign key relationship:opportunitylineitem.op

for (OpportunityLineItem oli:[SELECT OpportunityId,Product2.name
                              FROM OpportunityLineItem 
                              where ProductCode = null 
                              AND Opportunityid IN :opps]){
             Opportunity op = Trigger.newMap.get(oli.OpportunityId);
             // Account Acc = Trigger.newMap.get(oli.op.AccountId);
             lServ.add(new Services__c(
                     Account__c = op.accountid, 
                     Vendor__c =op.Issuing_Carrier__c,
                  // Source__c=Acc.Source__c,
                     End_Date__c= op.Expiration_Date__c,
    if (lServ.size() > 0){
        insert lServ;
  • Your trigger is on which object? I wonder how your can get an Opportunity and Account from same Map. BTW, the relation should opl.Opportunity.Account if you have retrieved it in your SOQL query
    – highfive
    Commented Aug 29, 2014 at 4:30
  • trigger is on opportunity object. I am new to this trigger area, so please help
    – user8132
    Commented Aug 29, 2014 at 4:34
  • 1
    Since you are already having the Opportunity object just get Account details from that.i.e. Source__c=op.Account.Source__c and same for any other Account fields
    – highfive
    Commented Aug 29, 2014 at 4:37
  • thank you so much, this helped me...if possible please suggest me any books to understand the relation between the objects and how to use them.
    – user8132
    Commented Aug 29, 2014 at 4:47
  • I have posted it as the answer below with more detail
    – highfive
    Commented Aug 29, 2014 at 5:22

1 Answer 1


Trigger.newMap will return a Map of triggered object with the new changes. So if you are writing the trigger on Opportunity, it will return a map of IDs to the new versions of the Opportunity records.
So after getting the Opportunity object from the Map, you are capable of retrieving it's parent with the existing relationships like below.

Account acc = op.Account;

Have a look at Trigger Context variables and note that,

this map is only available in before update, after insert, and after update triggers.

NOTE: Even though this is not directly relate to the question follow the best practices specially when writing triggers so that your trigger support bulk records and not hitting governor limits.

You must log in to answer this question.

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