+ Start a Discussion
Freedom EvansFreedom Evans 

Query for Product and opportunity Products ?

I'm trying to query for Product and their related opportunity products using the follow soql 

SELECT Id,Name,(SELECT Id FROM OpportunityLineItem) FROM Product2.  

However I get  this error message anytime I execute the code. 

Didn't understand relationship 'OpportunityLineItem' 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.

Schema show they are related in salesforce but I don't know why this query isnt working. 
Best Answer chosen by Freedom Evans
Naren9Naren9
Hi,
OpportunityLineItem is Junction Object between Opportunity and Product2.
We have the relationship name as OpportunityLineItems from Opportunity to OpportunityLineItem . You can find this is Workbench.
But when we check the relationship name from  Products2 to OpportunityLineItem, we didn't have the relationshipname. That's why we can't use the OpportunityLineItem from Products2.
User-added image
User-added image
Thanks,
Naren
 

All Answers

Naren9Naren9
Hi,
OpportunityLineItem is Junction Object between Opportunity and Product2.
We have the relationship name as OpportunityLineItems from Opportunity to OpportunityLineItem . You can find this is Workbench.
But when we check the relationship name from  Products2 to OpportunityLineItem, we didn't have the relationshipname. That's why we can't use the OpportunityLineItem from Products2.
User-added image
User-added image
Thanks,
Naren
 
This was selected as the best answer
Ajay K DubediAjay K Dubedi
Hi,

SELECT Id,Name,(SELECT Id FROM OpportunityLineItem) FROM Product2
This query never works because Opportunity Line Items are not the child of Products. It is a junction Object of Opportunity and Product2. Aggregate query use to fetch child in the relationship between object.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi

 
Freedom EvansFreedom Evans
Thanks Naren,  You description awnsered my question.