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
Rathna DeshmukhRathna Deshmukh 

how to query Product object based on Opportunity Object


I am looking for single SOQL to query Product object based on a field in Opportunity object.Below is our need.Please Please help and provide the query to acheive this.

Fetch the ProductCode and Name fields from Product object where Opportunity Id of OpportunityObject='xyz'.I tried below query it is throwing error:

SELECT Name,(SELECT Product_Code__c,Name from Product2) FROM Opportunity where Opportunity_ID__c = '006R0000008IEQI'

error:Didn't understand relationship 'Product2' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.

If I just execute the query(SELECT Product_Code__c,Name from Product2) it works,but when i combine it with Opportunity object it throws error.

Thanks a lot in advance!!
Deepak Kumar ShyoranDeepak Kumar Shyoran
If there is a relationship between Opportunity and Product for your organization then you need to use the ChildRelationsShip name instead of Product2.

In most cases it is Produts may different in you case just confirm from Product > Opportunity field > child relationship name
and then your SOQL will be like :
SELECT Name,(SELECT Product_Code__c,Name from Products) FROM Opportunity where Opportunity_ID__c = '006R0000008IEQI'