3

I'm using a SOQL to query the lookup relationships.

Primary Object: Opportunity

Secondary Object: Purchase__c.

From purchase__c we have a lookup to opportunity.

Field Name: Opportunity__c

Child Relationship Name: Purchases2

SOQL query:

for (Opportunity opp : [select Id, Name, (select id from Purchases2__r where Count__c>0) from Opportunity where Id IN :oppIds]) 

whats wrong with my query? getting error below:

If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name.

0

2 Answers 2

8

Verify the API Name of your child relationship as follows:

for (ChildRelationship relation : SObjectType.Opportunity.getChildRelationships())
    if (relation.getChildSObject() == Purchase__c.sObjectType)
        system.debug(relation.getRelationshipName());

Copy the output verbatim and use it where you have Purchases2__r.

4
  • 2
    Wish we had a useful code snippet library here on SFSE. Its little tidbits like these that keep being repeated that would be great to have outside of find the questions it is attached to.....but I guess there are other services for that....
    – Eric
    Commented Sep 16, 2016 at 18:43
  • I think It will help if the documentation feature ever gets rolled out here.
    – Adrian Larson
    Commented Sep 16, 2016 at 18:52
  • I think I should add a resource like that to my library, but I'd need more than just 1 sample.
    – sfdcfox
    Commented Sep 16, 2016 at 21:26
  • Generalized version: DescribeSObjectResult type = SobjectType.Account; String filter = 'Feed'; for (ChildRelationship relation : type.getChildRelationships()) { if (String.valueOf(relation).contains(filter)) system.debug('* ' + relation.getChildSObject() + ' = ' + relation.getRelationshipName()); } gist.github.com/shanekenyon87/38648262665500d4e7a479188e843110 Commented May 18, 2020 at 19:51
3

Go to your child object that is in the subquery, go to the lookup field, check the child relationship name. This is the name you must use in your subquery along with the __r. Also make sure there isn't more than one field that looks up to the parent and that you are using the correct field for your logic.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .