Search code examples
salesforcesoql

Child to Parent SOQL Query


I need a query between Opportunity and OpportunityLineItem.

OpportunityLineItem has a lookup for Opportunity. Child relationship name is OpportunityLineItems. Opportunity Lookup field is called OpportunityId.

I'm trying the below query but it doesn't work.

select Id,Name,OpportunityId__r.Description from OpportunityLineItem

Also tried:

select Id,Name,OpportunityLineItems__r.Description from OpportunityLineItem

Solution

  • Top-down

    SELECT Id, Name, Description,
        (SELECT Id, Name FROM OpportunityLineItems)
    FROM Opportunity
    

    Bottom-up

    SELECT Id, Name, Opportunity.Name, Opportunity.Description
    FROM OpportunityLineItem
    

    Check out the links in https://stackoverflow.com/a/73913839/313628 and https://stackoverflow.com/a/73877986/313628 too