Monday, March 12, 2018

Accessing Relationships with Apex

While attempting the first challenge for the Apex Specialist badge, I learned an important bit that helped me close the loop and finish the challenge successfully.

To access any related objects (look up, master-child), the API name that ends with __c is replaced by __r. For example, lets say class with name slave__c is under master__c, then an instance of the master class could access the slaves with syntax m.slave__r. Further, you can iterate through all the items with this syntax:
for(slave__c wp : m.slave__r){
    //awesome code here
}
We can do something similar for lookup relationships. Note when the relationship is not one to many (as is with most look ups for the class doing the look up), __r yields a single object rather than a list.

1 comment: