Search code examples
nestedsalesforcesoql

How can I build an SOQL query for 3 level object?


Its Master parent> child> child of object2

I just basically wanted to get all the Id and names from the Child of object2.

Tried this but I am getting 'Unknown error parsing query' SELECT Id, name (SELECT id, name FROM child of object_2) from child


Solution

  • completely "bottom-up"

    SELECT Id
    FROM Child2__c
    WHERE Child1__r.Master__c = '...'
    

    or you were close

    SELECT Id, Name,
    (SELECT Id, Name FROM Children2__r)
    FROM Child1__c
    WHERE Master__c = '...'
    

    (but for this you'll have to be sure what's the relationship name between child1 and 2)

    Edit after OP provided exact relationship names

    Bottom up would be

    SELECT Id, Name
    FROM Event_Expense_Detail__c
    WHERE Service_Order__r.Ford_Field_Event__c = 'one master id goes here'
    

    You start from the lowest point (detail) then go "up" with dot notation once to Event Expense and then "up" again. If you still don't feel it - try

    SELECT 
        Service_Order__r.Ford_Field_Event__r.Id, Service_Order__r.Ford_Field_Event__r.Name,
        Service_Order__r.Id, Service_Order__r.Name,
        Id, Name
    FROM Event_Expense_Detail__c 
    ORDER BY Service_Order__r.Ford_Field_Event__r.Name, Service_Order__r.Name, Name
    LIMIT 100
    

    Top-down is limited, you can go 1 level down. So we'd have

    SELECT 
        Ford_Field_Event__r.Id, Ford_Field_Event__r.Name,
        Id, Name,
        (SELECT Id, Name FROM Service_Order_Items__r)
    FROM Event_Expense__c
    WHERE Ford_Field_Event__c = 'one master id goes here'