[SalesForce] Having Trouble with Parent-to-Child lookup/SOQL Query

I have two objects

Request__c and Matter__c

These two objects have a lookup relationship where Request__c is a lookup field on Matter__c. So a single Request record can have multiple Matter records.

I’m trying to write a SOQL query on the Request to pull all Matters associated with each Request. My query is as follows:

SELECT Id, Name, (SELECT Id, Status__c, Matter_Type__c FROM Matters__r) FROM Request__c

But whenever I try running this I get the following error:

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

I thought that if there was a lookup field on the Matter__c object, then a relationship between the 2 objects would exist and I could query to pull all the children (Matters) for a given Request.

I’ve checked the field in Setup -> Create -> Objects -> Matter__c and it provides the following information:

Related List Label: Matters

Child Relationship Name: Request

Can someone help me sort this out?

Best Answer

You can get the API Name of the child relationship as follows via Execute Anonymous:

for (ChildRelationship relationship : SObjectType.Request__c.getChildRelationships())
    if (relationship.getChildSObject() == Matter__c.sObjectType)
        system.debug(relationship.getRelationshipName());

Copy this value verbatim and replace Matters__r.

Related Topic