function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Glenn DalyGlenn Daly 

Referencing product2 record from Opoortunity object

I'm trying to reference the product2 name from an opportunity record. However it's giving me this error and not allowing me to save the code.

"Invalid foreign key relationship: Opportunity.opportunitylineitem"

How should I be referencing this field?

global class OpOwnerOldService_Scheduled Implements Schedulable
    {
        global void execute(SchedulableContext sc)
        {
            sendEmailtoOppOwner();
        }

        public void sendEmailtoOppOwner()
        {
            List<Opportunity> listOpportunity = new List<Opportunity>();
            listOpportunity = [SELECT Id, OwnerId FROM Opportunity WHERE Id In (SELECT OpportunityId FROM OpportunityLineItem WHERE Product2.Make_unavailable_for_opps_and_proposals__c = TRUE)];

            for(Opportunity opp : listOpportunity)
            {
               Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setTargetObjectId(opp.OwnerId);
mail.setReplyTo('glenn.daly@live.com');
mail.setSenderDisplayName('Salesforce Support');
mail.setSubject('Historic Service attached to current opportunity : '+ opp.  );
mail.setPlainTextBody(opportunity.Id +' has been created.');
mail.setSaveAsActivity(false);
                
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }

            update listOpportunity;
        }
    }
sridharbsridharb
Hi Glenn,

I tried your query at my sandbox works fine, didn't throw any error. Something is missing, i think so there is no wrong in SOQL.

I tried this 
List<Opportunity> a = [select id, ownerId from opportunity where id in (SELECT OpportunityId FROM OpportunityLineItem WHERE Product2.family='Cloud')];

Good Luck. Check security settings. As we know salesforce error description not always so precise.
Regards
Sri