7

Let's say I have 2 custom objects: Person and Award. Award has a lookup field to Person called Receiver.

If I query an object of Award, I know I can do Award.Receiver__r to access fields of the related Person. Is it possible to do the reverse - provided I know that a specific Person object has an Award (i.e. an Award exists whose lookup field specifies that person), can I access the fields of that Award via a field on Person object in Apex and/or SOQL?

1 Answer 1

13

Yes. You are looking for a Left Outer Join, where the type of query you first reference is a Right Outer Join. Your query might look like:

SELECT (SELECT Id FROM Awards__r) FROM Person__c

You can control the value of this Child Relationship Name in the configuration on the lookup field. Custom lookups append __r to the relationship name. When configuring the lookup definition, this option will be on Step 3 of the configuration wizard.

Sample Lookup Configuration (create)

You can also change it later by editing the field.

Sample Lookup Configuration (edit)


You can verify the child relationship to use programmatically (where I guessed it might be Awards__r) using this snippet in Execute Anonymous:

for (ChildRelationship relation : SObjectType.Person__c.getChildRelationships())
    if (relation.getChildSObject() == Award__c.sObjectType)
        system.debug(relation.getRelationshipName()); // use this output verbatim

Note that while you can treat this sub-query like a field, it contains a List<Award__c> in this instance.

Person somePerson = [SELECT (SELECT Id FROM Awards__r) FROM Person__c LIMIT 1];
List<Award__c> awards = somePerson.Awards__r;
// you can also get it dynamically
awards = somePerson.getSObjects('Awards__r');
0

You must log in to answer this question.

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